英文:
How to unite second level ManyToManyFields?
问题
以下是翻译的代码部分:
class Tag(models.Model):
name = models.CharField(max_length=50)
class Element(models.Model):
tags = models.ManyToManyField('Tag')
class Category(models.Model):
elements = models.ManyToManyField('Element')
@property
def tags(self):
... # how can I do this?
希望这对你有所帮助。如果有任何其他疑问,请随时提出。
英文:
I have models as follows:
class Tag(models.Model):
name = models.CharField(max_length=50)
class Element(models.Model):
tags = models.ManyToManyField('Tag')
class Category(models.Model):
elements = models.ManyToManyField('Element')
@property
def tags(self):
... # how can I do this?
How can I get the union of all the tags that appear in elements of a given category?
I could do something like this:
def tags(self):
all_tags = Tag.objects.none()
for element in self.elements.all():
all_tags = all_tags | element.tags.all()
return all_tags.distinct()
But is there a way to do this directly at database level?
答案1
得分: 3
使用双下划线符号来遍历关系:
def tags(self):
return Tag.objects.filter(element__category=self)
英文:
Use the double underscore notation to traverse relations:
def tags(self):
return Tag.objects.filter(element__category=self)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论