其他分享
首页 > 其他分享> > 如何在Django中创建具有额外字段对称的递归ManyToManyField关系?

如何在Django中创建具有额外字段对称的递归ManyToManyField关系?

作者:互联网

class Food_Tag(models.Model):
    name = models.CharField(max_length=200)
    related_tags = models.ManyToManyField('self', blank=True, symmetrical=False, through='Tag_Relation')

    def __unicode__(self):
     return self.name

class Tag_Relation(models.Model):
    source = models.ForeignKey(Food_Tag, related_name='source_set')
    target = models.ForeignKey(Food_Tag, related_name='target_set')
    is_a = models.BooleanField(default=False); # True if source is a target
    has_a = models.BooleanField(default=False); # True if source has a target

我希望能够得到Food_Tags之间的关系:

>>> steak = Food_Tag.objects.create(name="steak")
>>> meat = Food_Tag.objects.create(name="meat")
>>> r = Tag_Relation(source=steak, target=meat, is_a=True)
>>> r.save()
>>> steak.related_tags.all()
[<Food_Tag: meat>]
>>> meat.related_tags.all()
[]

但是related_tags对于肉是空的.我意识到这与’symmetrical = False’参数有关,但我怎样才能设置模型,使’meat.related_tags.all()’返回所有相关的Food_Tags?

解决方法:

the docs中所述:

  • When defining a many-to-many relationship from a model to
    itself, using an intermediary model, you must use
    07001 (see
    07002).

因此,在Django中,(还有?)可能与额外的字段具有对称的,递归的多对多关系.这是一个“挑选两个”的交易.

标签:python,django,manytomanyfield
来源: https://codeday.me/bug/20190610/1212331.html