一、我们现在有这么个数据模型关系
我有四个对像:作者,作者详情,出版社,书籍,那关系模型建模
具体如下图
二、现在创建表格:
重点问题我加了注释!!敲黑板!!一定注意!!
from django.db import models
# Create your models here.
class Author(models.Model):
author_name = models.CharField(max_length=8, null=False)
class AuthorDetail(models.Model):
author_sex = models.IntegerField(choices=((0, "男"), (1, "女")), null=False)
author_phone = models.CharField(max_length=11,null=False)
author_age = models.IntegerField(null=False)
#一对一关系的两个类,关系模型写到哪个类里都行,但是代码是顺序执行的,如果放在第一个类,在执行
#到对应表格时,还没有创建,所以要写到第二个类里
#models.CASCADE是级联删除,即关系方数据删掉,本表的相关信息也一并删掉,可参考前面的外键博客
author = models.OneToOneField(to=Author,to_field="id",on_delete=models.CASCADE)
class Publisher(models.Model):
publisher_name = models.CharField(max_length=30,null=False)
publisher_address = models.CharField(max_length=50,null=False)
publisher_city = models.CharField(max_length=30,null=False)
publisher_website = models.URLField(null=True)
class Book(models.Model):
book_name = models.CharField(max_length=20,null=False)
#多对多关系与一对一关系同理,写到哪个都行,也是顾及代码执行顺序,要写到下面的类里
author = models.ManyToManyField(to=Author)
#一对多关系,要写到多的类里
publisher = models.ForeignKey(to=Publisher,to_field="id",on_delete=models.CASCADE)
price = models.FloatField(max_length=6,null=None)