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?