Django 1.8 - Intermediary Many-to-Many-Through Relationship - What is the consequence of where 'ManytoManyField' is used?

前端 未结 2 1831
离开以前
离开以前 2021-02-08 04:47

An example Many-to-Many through relationship in Django:

class First(models.Model):
    seconds = models.ManyToManyField(Second, through=\'Middle\')

class Middle         


        
2条回答
  •  旧时难觅i
    2021-02-08 05:22

    When you add a many to many field to a model a separate table is created in the database that stores the links between two models. If you don't need to store any extra information in this third table then you don't have to define a model for it.

    class First(models.Model):
        seconds = models.ManyToManyField(Second, related_name='firsts')
    
    class Second(models.Model):
        pass
    

    I can't think of any difference between defining the many to many field in the First or Second models:

    class First(models.Model):
        pass
    
    class Second(models.Model):
        firsts = models.ManyToManyField(First, related_name='seconds')
    

    In both cases usage is the same:

    firsts = my_second.firsts
    seconds = my_first.seconds
    

提交回复
热议问题