Django Bi-directional ManyToMany - How to prevent table creation on second model?

前端 未结 4 710
情书的邮戳
情书的邮戳 2021-01-31 05:51

I have two models, each has a shared ManyToMany, using the db_table field. But how do I prevent syncdb from attempting to create the shared table, for the second model?

4条回答
  •  青春惊慌失措
    2021-01-31 06:12

    You don't need to put a ManyToManyField on both sides of the relation. Django will do that for you.

    You probably want something more like this:

    class Model1(models.Model):
        name = models.CharField(max_length=128)
        ...
    
    class Model2(models.Model):
        name = models.CharField(max_length=128)
        othermodels = models.ManyToManyField(Model1, through='Model1Model2')
        ...        
    
    class Membership(models.Model):
        class Meta:
            db_table = 'model1_model2'
        model1 = models.ForeignKey(Model1)        
        model2 = models.ForeignKey(Model2)
    

    When you're working with your models, an instance of Model1 will have a othermodels_set field which is automatically added by django. Instances of Model2 will have othermodels.

提交回复
热议问题