1

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

2 Answers 2

2

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__'
Sign up to request clarification or add additional context in comments.

3 Comments

Can you check out the updated post? I tried your codes, but it has some issue.
@Jay try it with similarstore_set (not similarstores_set).
Stunning! Thanks :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.