Zakaria Talhami
Zakaria Talhami

Reputation: 116

Filter many to many set from models instance

I have a product model that has tags, the tags can be in multiple languages. when I get a instance of the product, i have a product.tags manager.

I was wondering if there was a way to filter the tags connected to the product instance, that when I pass it to the serializer, i would only get the tags in a single language with the serializer output.

class Product(models.Model):
   ...
   tags = models.ManyToManyField(Tag)
   ...


class Tag(models.Model)
   text = models.CharField(max_length=32)
   language = models.CharField(max_length=2)


class ProductSerializer(serializer.ModelSerializer):
   tags = TagSerializer(many=True)
   ...

I am able to filter them manually then add them to the data response, like so:

tags_query = product.tags.filter(language=lang)
tag_serializer = TagSerializer(lang, many=True) 

but I was wondering if this can be done through the serializers?

Upvotes: 0

Views: 22

Answers (1)

Minh Nguyen
Minh Nguyen

Reputation: 31

No, you can't do that through the serializers. You can do like this:

tags_query = product.tags.filter(language=lang)
tag_serializer = TagSerializer(tags_query, many=True) 

Upvotes: 1

Related Questions