Detailed explanation of three ways to create Django many to many table relationship

  • 2021-11-24 02:05:02
  • OfStack

Directory 1, Mode 1: Auto Creation 2, Mode 2: Pure Manual Creation 3. Mode 3: Semi-automatic creation

1. Mode 1: Automatically create


# django orm  Automatically help us create the first 3 A form, mine app The name is app01,  The name of the table is: app01_book_authors
#  This way can make Django Help us build it quickly 1 Zhang relational table, the advantage is that cross-table query can be carried out through this table, but the disadvantage is 1 A virtual table has poor expansibility. 

#  Book list 
class Book(models.Model):
    name = models.CharField(max_length=32)
    authors = models.ManyToManyField(to='Author')

#  Author list 
class Author(models.Model):
    name = models.CharField(max_length=32)

2. Mode 2: Create manually


#  This way can't pass orm Cross-table query (not recommended) 

#  Table 1
class Book(models.Model):
    name = models.CharField(max_length=32)

#  Table 2
class Author(models.Model):
    name = models.CharField(max_length=32)

#  Table 3
class Book2Author(models.Model):
    book = models.ForeignKey(to='Book')
    author = models.ForeignKey(to='Author')
    info = models.CharField(max_length=32)

3. Mode 3: Semi-automatic creation


#  High scalability and can conform to orm Query 

class Book(models.Model):
    name = models.CharField(max_length=32)
    #  No. 1 3 How to create a table 
    authors = models.ManyToManyField(to='Author', through='Book2Author', through_fields=('book', 'author'))
    # through  Tell  django orm  The many-to-many relationship between book list and author list is through  Book2Author  Table to record 
    # through fields  Tell  django orm  Recording relationships is done using  Book2Author  In the table  book  Field   And  author Field   To record 
    #  In which table is this relationship written, through_fields Which table should be written first in ( That field ) Lowercase of 
    #  However, many-to-many field  add set remove clear 4 One method won't work 


class Author(models.Model):
    name = models.CharField(max_length=32)


class Book2Author(models.Model):
    book = models.ForeignKey(to='Book')
    author = models.ForeignKey(to='Author')
    info = models.CharField(max_length=32)

Related articles: