Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST Framework - query limit on nested serializer?

I have a situation in which one table is related to another via a foreign key as follows:

models.py

class Container(models.Model):
    size  = models.CharField(max_length=20)
    shape = models.CharField(max_length=20)

class Item(models.Model):
    container = models.ForeignKey(Container, related_name='items')
    name  = models.CharField(max_length=20)
    color = models.CharField(max_length=20)

serializers.py

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item


class ContainerSerializer(serializers.ModelSerializer):
    items = ItemSerializer(many=True)

    class Meta:
        model = Container
        fields = ('size', 'shape', 'items')

This works fine, but my problem is that all the items in the container get serialized. I only want items with color='green' to be serialized.

like image 636
tadasajon Avatar asked Aug 13 '14 18:08

tadasajon


2 Answers

class ContainerSerializer(serializers.ModelSerializer):
    items = serializers.SerializerMethodField()

    def get_items(self, obj):
        query = Item.objects.filter(item_set__color='green')
        serializer = ItemSerializer(query, many=True)
        return serializer.data

    class Meta:
        model = Container
        fields = ('size', 'shape', 'items')
like image 116
xleon Avatar answered Sep 19 '22 23:09

xleon


Instead of changing how serializer works, a simplier way, its just filter you Container with green color items and them try to serialize it

You can do something like this:

container_objects = Container.objects.filter(id='your_container_id',item_set__color='green')
serialized_containers = YourContainerSerializer(data=container_objects)
like image 23
levi Avatar answered Sep 17 '22 23:09

levi