如何合并第二级的ManyToManyFields?

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

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)

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:

确定