Three ways to create Django many-to-many table relationships

Method 1: Automatic creation

# Django ORM automatically help us create the third table, my app name is app01, the table name: app01_book_authors 
# This way you can make Django quickly to help us build a table out, the benefits can be through this table Cross-table query, the disadvantage is a virtual table, poor scalability.

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

Method 2: Purely manual creation

# This way can not be cross-table queries by orm (not recommended)

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

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)

Method 3: Semi-automatic creation

# Scalability high, and able to meet orm inquiry

class Book(models.Model):
    name = models.CharField(max_length=32)
    authors = models.ManyToManyField(to='Author', through='BookAndAuthor') 

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

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

Leave a Reply