Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
529 views
in Technique[技术] by (71.8m points)

Django rest framework - filtering for serializer field

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.

What should I do?

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)
question from:https://stackoverflow.com/questions/28309507/django-rest-framework-filtering-for-serializer-field

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about something like this:

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 omitted for brevity. Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...