Django 通过多对多额外字段获取查询集
Django get queryset through Many To Many extra field
我有两个 类 对象之间的多对多关系,我需要通过多对多额外字段过滤查询集
那是我的 3 类
class Card(models.Model):
title = models.CharField(max_length=250 )
tags = models.ManyToManyField(Tag, through='Cards_Tags')
class Tag(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
class Cards_Tags(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
card = models.ForeignKey(Card, on_delete=models.CASCADE)
field = models.CharField( max_length=25, blank=True )
如果我使用它,它会起作用,但它 returns 一个 Cards_Tags 的查询集,我需要与标签对象相同的结果
developers = Cards_Tags.objects.filter(card=obj, field='developer')
如何获取标签查询集,其中 Cards_Tags 中的 m2m 关系具有字段='developer'?
您可以过滤:
Tag.objects.filter(<strong>cards_tags__card=obj, cards_tags__field='developer'</strong>)
或者您可以完成 ManyToManyField
:
obj<strong>.tags</strong>.filter(<strong>cards_tags__field='developer'</strong>)
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from Cards_Tags
to CardTag
. In that case you filter with obj.tags.filter(cardtag__field='developer')
我有两个 类 对象之间的多对多关系,我需要通过多对多额外字段过滤查询集
那是我的 3 类
class Card(models.Model):
title = models.CharField(max_length=250 )
tags = models.ManyToManyField(Tag, through='Cards_Tags')
class Tag(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
class Cards_Tags(models.Model):
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
card = models.ForeignKey(Card, on_delete=models.CASCADE)
field = models.CharField( max_length=25, blank=True )
如果我使用它,它会起作用,但它 returns 一个 Cards_Tags 的查询集,我需要与标签对象相同的结果
developers = Cards_Tags.objects.filter(card=obj, field='developer')
如何获取标签查询集,其中 Cards_Tags 中的 m2m 关系具有字段='developer'?
您可以过滤:
Tag.objects.filter(<strong>cards_tags__card=obj, cards_tags__field='developer'</strong>)
或者您可以完成 ManyToManyField
:
obj<strong>.tags</strong>.filter(<strong>cards_tags__field='developer'</strong>)
Note: Models in Django are written in PascalCase, not snake_case, so you might want to rename the model from
toCards_Tags
CardTag
. In that case you filter withobj.tags.filter(cardtag__field='developer')