Multiple many-to-many relations to the same model in Django

前端 未结 2 414
时光取名叫无心
时光取名叫无心 2021-02-05 03:25

Given the following model with two many-to-many relations:

class Child(models.Model):
    name = models.CharField(max_length=80)

class Foo(models.Model):
    ba         


        
2条回答
  •  情话喂你
    2021-02-05 03:43

    I think you need to just give the two fields different related_names:

    class Child(models.Model):
      name = models.CharField(max_length=80)
    
    class Foo(models.Model):
      bar = models.ManyToManyField(Child, related_name="bar")
      baz = models.ManyToManyField(Child, related_name="baz")
    

    If you don't give a related name, then it's trying to create the same accessor name (foo_set) twice on the Child model. If you give the same related name, it's again going to try to create the same accessor twice, so you need to give unique related names. With the above code to define your models, then given a Child instance c, you can access related Foo objects with c.bar.all() and c.baz.all().

    If you don't want the backwards relations, then append a + to each of the (unique) related names:

    class Foo(models.Model):
      bar = models.ManyToManyField(Child, related_name="bar+")
      baz = models.ManyToManyField(Child, related_name="baz+")
    

提交回复
热议问题