本文介绍了如何使Django中具有额外字段对称的递归ManyToManyField关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
$ _ code> class Food_Tag(models.Model):name = models.CharField(max_length = 200)
related_tags = models.ManyToManyField('self',blank =真的,对称= False,通过='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) ; #如果source是目标,则为true
has_a = models.BooleanField(default = False); #如果source有目标,则为true
我想要获得Food_Tag之间的关系,如:
>>> 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对于肉是空的。我意识到这与'symmetry = False'参数有关,但是如何设置模型,使得meat.related_tags.all()返回所有相关的Food_Tag?
解决方案
如:
因此,在Django中,不可能有一个与多余字段对称的递归多对多关系。这是一个选择二的排序。
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
I want to be able to get the relations between Food_Tags like:
>>> 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()
[]
but related_tags is empty for meat. I realize this has to do with the 'symmetrical=False' argument, but how can I set up the model such that 'meat.related_tags.all()' returns all related Food_Tags?
解决方案
As mentioned in the docs:
Thus, it is not (yet?) possible to have a symmetrical, recursive many-to-many relationship with extra fields, in Django. It's a "pick two" sorta deal.
这篇关于如何使Django中具有额外字段对称的递归ManyToManyField关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!