简体   繁体   English

如何订购 Django SerializerMethodField with ManytoManyField Count

[英]How to Ordering Django SerializerMethodField with ManytoManyField Count

I want to make blog web, I want to order on a computed SerializerMethodField, such as likes_count.我想做博客 web,我想订购一个计算出来的 SerializerMethodField,比如 likes_count。 Here are my Code这是我的代码

models.py模型.py

class Post(models.Model):
   title =  models.CharField(max_length=255, unique=True)
   content = models.TextField()
   like = models.models.ManyToManyField(
        settings.AUTH_USER_MODEL, related_name='likes', blank=True)

serializer.py序列化程序.py

class PostSerializer(serializers.ModelSerializer):
   likes_count = serializer.SerializerMethodField()
   

   class Meta:
      model = Post
      fields =[ 'title, content, likes' ]

  def get_likes_count(self, obj):
        return obj.like.count()
        

views意见

class PostGenericAPIView(generics.GenericAPIView):
   queryset = Post.objects.all()
   serializer_class = PostSerializer
   filter_backends = (filters.OrderingFilter)

You can just annotate the value of count and order by it.您可以通过它来annotate count 和 order 的值。 For example:例如:

from django.db.models import Count


class PostGenericAPIView(generics.GenericAPIView):
   queryset = Post.objects.annotate(likes_count=Count('like')).order_by('likes_count')
   serializer_class = PostSerializer
   filter_backends = (filters.OrderingFilter)

Also, to reduce DB hits, you can directly access the value of likes_count in serializer:此外,为了减少 DB 命中,您可以在序列化程序中直接访问likes_count的值:

class PostSerializer(serializers.ModelSerializer):
   likes_count = serializers.IntegerField()  # No need for serializer method field

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM