Store
具有SimilarStore
的外键。通常,similarstore_set
中大约有一百家类似的商店。当我使用similarstore_set
制作API时,是否有一种方法可以限制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__'
更新
以下代码抛出'Store' object has no attribute 'similarstores_set'
,实际上却有similarstore_set
,为什么抛出错误?
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__'
答案 0 :(得分:0)
您可以为serializers.SerializerMethodField()
添加一个similarstore_set
并定义一个查询SimilarStore
数据并设置similarstore_set
的方法。您可以通过将上下文传递给序列化器来传递similarstore_set
中所需的元素数。参见https://www.django-rest-framework.org/api-guide/serializers/#including-extra-context
答案 1 :(得分:0)
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__'