Django 之 ORM表之间的外键关联与多对多

实现环境表结构:

Django 之  ORM表之间的外键关联与多对多

models.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=64,null=False,unique=True)

    def __str__(self):
        return "publisher_name:{}".format(self.name)

class Book(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=128,null=False)
    publisher = models.ForeignKey(to=Publisher)           #外键关联

    def __str__(self):
        return "book_title:{}".format(self.title)

class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16,null=False)
    book = models.ManyToManyField(to="Book")            #跟BOOK多对多关系

    def __str__(self):
        return "author_name:{}".format(self.name)

猜你喜欢

转载自blog.51cto.com/12965094/2392068
今日推荐