Python - Django - Table of many association table books

models.py Code:

django.db Import Models from 

# the Create your Models here Wallpaper. 


# Press 
class Publisher (models.Model): 
    id = models.AutoField (primary_key = True) # auto-incrementing primary key id 
    only does not create a # varchar (64) of empty field 
    name = models.CharField (= 64 MAX_LENGTH, null = False, UNIQUE = True) 

    DEF __str __ (Self): 
        return "<Object Publisher: {}>." the format (the self.name) 


# Books 
class book ( models.Model): 
    ID = models.AutoField (primary_key = True) # increment the primary key ID 
    # Create a varchar (64) is not the only empty fields 
    title = models.CharField (max_length = 64, null = False, unique = True) 
    foreign key field and press # associated 
    Publisher = models.ForeignKey (to = "Publisher") 

    DEF __str __ (Self):
        return "<Book object: {}>".format(self.title)


# 作者
class Author(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=16, null=False, unique=True)
    book = models.ManyToManyField(to="Book")  # 多对多关联 Book 表,ORM 会自动生成第 3 张表

    def __str__(self):
        return "<Author object: {}>".format(self.name)

Then execute the command, generating a table

It generates two tables

Add field

Here id has written two books for authors 1, id 2,3 authors wrote a book together

 

Guess you like

Origin www.cnblogs.com/sch01ar/p/11238135.html