Jay P.
Jay P.

Reputation: 2590

How to limit the number of objects given from nested serialization

Store has a foreign key to SimilarStore. Normally, there is about a hundred of similar stores in similarstore_set. Is there a way to limit the number of similar stores in similarstore_set when I make API with Django REST Framework?

serializer.py

class SimilarStoreSerializer(ModelSerializer):

    class Meta:
        model = SimilarStore
        fields = ('domain', )


class StoreSerializer(ModelSerializer):

    similarstore_set = SimilarStoreSerializer(many=True)

    class Meta:
        model = Store
        fields = '__all__'

UPDATE

The following codes throws 'Store' object has no attribute 'similarstores_set', it actually has similarstore_set, why is it throwing the error?

class StoreSerializer(ModelSerializer):

    image_set = ImageSerializer(many=True)
    promotion_set = PromotionSerializer(many=True)

    similar_stores = SerializerMethodField()

    def get_similar_stores(self, obj):
        # get 10 similar stores for this store
        stores = obj.similarstores_set.all()[:10]  <-- This line throws the error
        return SimilarStoreSerializer(stores, many=True).data

    class Meta:
        model = Store
        fields = '__all__'

Upvotes: 1

Views: 1516

Answers (2)

slider
slider

Reputation: 12990

You can use a SerializerMethodField to perform a custom lookup and limit the number of records:

class StoreSerializer(ModelSerializer):
    similar_stores = serializers.SerializerMethodField()

    def get_similar_stores(self, obj):
        stores = obj.similarstore_set.all()[:10] # get 10 similar stores for this store
        return SimilarStoreSerializer(stores, many=True).data

    class Meta:
        model = Store
        fields = '__all__'

Upvotes: 2

Red Cricket
Red Cricket

Reputation: 10470

You could add a serializers.SerializerMethodField() for similarstore_set and define a method that would query the SimilarStore data and set similarstore_set. You could pass the number of elements you want in similarstore_set by passing context to your serializer. see https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context

Upvotes: 0

Related Questions