How to make recursive ManyToManyField relationships that have extra fields symmetrical in Django?

前端 未结 5 753
后悔当初
后悔当初 2020-12-18 07:53
class Food_Tag(models.Model):
    name = models.CharField(max_length=200)
    related_tags = models.ManyToManyField(\'self\', blank=True, symmetrical=False, through=         


        
5条回答
  •  青春惊慌失措
    2020-12-18 08:29

    Since you didn't explicitly say that they need to be asymmetrical, the first thing I'll suggest is setting symmetrical=True. This will cause the relation to work both ways as you described. As eternicode pointed out, you can't do this when you're using a through model for the M2M relationship. If you can afford to go without the through model, you can set symmetrical=True to get exactly the behavior you describe.

    If they need to remain asymmetrical however, you can add the keyword argument related_name="sources" to the related_tags field (which you might want to consider renaming to targets to make things more clear) and then access the related tags using meat.sources.all().

提交回复
热议问题