文章目录
ORM
-
ORM简介
Object Relation Mapping
django中使用Mysql时
对象映射关系
把数据库中的数据通过Django中的模型系统,可以转换为python中可操作的类的对象。所以叫映射关系。
-
ORM项目使用MySql数据库
setting.py中设置
与setting同级的__init__.py中设置
from django.db import models
# Create your models here.
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
# 设置外键,一对多
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=20)
publisher = models.ForeignKey(to='Publisher')
# 多对多,新建一个联合表
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20)
book = models.ManyToManyField(to='Book')
'''
相当于:
class Author2Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.ForeignKey(to='Author')
book = models.ForeignKey(to='Book')
'''
to='表名‘在本文件中反射此文件的模型,如果要关联别的app中的model。直接导入表后,to=表名
在models中新建外键,一对多,多对多的类,也就是表
在终端运行更新日志和把python语言通过django框架翻译成mysql看得懂的语言,新建表
D:\学习资料\Daily Code and experience\day59\day59>python manage.py makemigrations
Migrations for 'app01':
app01\migrations\0001_initial.py
- Create model Author
- Create model Book
- Create model Publisher
- Add field publisher to book
- Add field book to author
D:\学习资料\Daily Code and experience\day59\day59>python manage.py migrate;
Unknown command: 'migrate;'
Type 'manage.py help' for usage.
D:\学习资料\Daily Code and experience\day59\day59>python manage.py migrate
Operations to perform:
Apply all migrations: admin, app01, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying app01.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying sessions.0001_initial... OK
数据库查询结果
mysql> use day59;
Database changed
mysql> show tables;
Empty set (0.00 sec)
mysql