Django get queryset through Many To Many extra field

Viewed 84

i have a Many-to-Many Relationship between two classes object, i need get queryset filtered by a Many-To-Many extra field

that are my 3 classes

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 )

if i use that it works, but it returns a queryset of Cards_Tags i need same result as Tags objects

developers = Cards_Tags.objects.filter(card=obj, field='developer')

how i can get Tags queryset where m2m relationship in Cards_Tags have field='developer' ?

1 Answers

You can filter with:

Tag.objects.filter(cards_tags__card=obj, cards_tags__field='developer')

or you can work through the ManyToManyField:

obj.tags.filter(cards_tags__field='developer')

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')

Related