如何实现django orm创建关系表?

在这里插入图片描述
在这里插入图片描述
三种关系见注释:

from django.db import models
class Book(models.Model):
    #id字段会自动创建,就不写了
    title = models.CharField(max_length = 64)
    #小数字段。总位数共8位占2位
    price = models.DecimalField(max_digits = 8,decimal_places = 2)

    #书籍和出版社是一对多的外键关系。外键要定义在多的一方
    publish = models.ForeignKey(to = "Publish")
    #书籍和作者是多对多的外键关系。外键要定义在多的一方
    authors = models.ManyToManyField(to = "Author")
    """
       authors字段是一个虚拟字段 不会真正的在表中创建出来
       只是用来告诉django orm 需要创建书籍和作者的第三张关系表
    """


class Publish(models.Model):
    name = models.CharField(max_length = 64)
    addr = models.CharField(max_length = 64)

class Author(models.Model):
    name = models.CharField(max_length = 32)
    phone = models.BigIntegerField()
    #作者和作者详情是一对一的外键关系
    author_detail = models.OneToOneField(to = "AuthorDetail")

class AuthorDetail(models.Model):
    age = models.IntegerField()
    addr = models.CharField(max_length = 255)
发布了478 篇原创文章 · 获赞 673 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/YJG7D314/article/details/103860684