如何合并第二级的ManyToManyFields?

huangapple go评论91阅读模式
英文:

How to unite second level ManyToManyFields?

问题

以下是翻译的代码部分:

  1. class Tag(models.Model):
  2. name = models.CharField(max_length=50)
  3. class Element(models.Model):
  4. tags = models.ManyToManyField('Tag')
  5. class Category(models.Model):
  6. elements = models.ManyToManyField('Element')
  7. @property
  8. def tags(self):
  9. ... # how can I do this?

希望这对你有所帮助。如果有任何其他疑问,请随时提出。

英文:

I have models as follows:

  1. class Tag(models.Model):
  2. name = models.CharField(max_length=50)
  3. class Element(models.Model):
  4. tags = models.ManyToManyField('Tag')
  5. class Category(models.Model):
  6. elements = models.ManyToManyField('Element')
  7. @property
  8. def tags(self):
  9. ... # 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:

  1. def tags(self):
  2. all_tags = Tag.objects.none()
  3. for element in self.elements.all():
  4. all_tags = all_tags | element.tags.all()
  5. return all_tags.distinct()

But is there a way to do this directly at database level?

答案1

得分: 3

使用双下划线符号来遍历关系:

  1. def tags(self):
  2. return Tag.objects.filter(element__category=self)
英文:

Use the double underscore notation to traverse relations:

  1. def tags(self):
  2. return Tag.objects.filter(element__category=self)

huangapple
  • 本文由 发表于 2023年2月27日 07:00:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75575512.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定