Django Rest Framework-筛选序列化器字段 [英] Django rest framework - filtering for serializer field
本文介绍了Django Rest Framework-筛选序列化器字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对Django REST-full框架有疑问。
I have question about Django REST-full framework.
当产品呈现到远程客户端时,每个产品都将包含过滤数据。
When products have rendered into remote client, each of product takes a filed with filtered data.
例如,模型可能像这样。
For example, model may be like this.
class Product(models.Model):
name = models.CharField()
class Like(models.Model):
product = models.ForeignKey(Product, related_name="likes")
在客户上,每喜欢的产品均以真实值而非错误值进行计数。
On the client, each likes of product counted with true value, not false.
所以我在序列化器中尝试了以下代码。
So I tried with below code in the serializer.
class ProductSerializer(serializers.ModelSerializer):
likes = serializers.PrimaryKeyRelatedField(many=True, queryset=Like.objects.filter(whether_like=True))
class Meta:
model = Product
fields = ('id', 'name', 'likes')
但是,这不符合我的期望。
But, that is not working as I wanted.
我该怎么办?
以下是额外的视图代码。
The following is extra view code.
@api_view(['GET'])
def product_list(request, user_id, format=None):
if request.method == 'GET':
products = Product.objects.all()
serializer = ProductSerializer(products, many=True)
return Response(serializer.data)
推荐答案
这样的事情怎么样:
class ProductSerializer(serializers.ModelSerializer):
likes = serializers.SerializerMethodField('get_likes')
def get_likes(self, product):
qs = Like.objects.filter(whether_like=True, product=product)
serializer = LikeSerializer(instance=qs, many=True)
return serializer.data
class Meta:
model = Product
fields = ('id', 'name', 'likes')
** LikeSerializer $ c $为简洁起见,省略了c>。希望这可以帮助。
**LikeSerializer
omitted for brevity. Hope this helps.
这篇关于Django Rest Framework-筛选序列化器字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文