过滤帖子大于一定数量的喜欢

Filtering Posts greater than certain number of likes

我有一个关于按喜欢计数大于给定数字过滤帖子的问题。

我想在 DJANGO 上实现 SHELL 当我输入 post.likes 大于 10 我想查看所有超过 10 个赞的帖子。

我该怎么做?

谢谢

models.py

class Post(models.Model,HitCountMixin):
  likes = models.ManyToManyField(User, related_name="likes", blank=True)

您可以使用 .annotate() [Django-doc] and then .filter(…) [Django-doc]:

from django.db.models import Count

Post.objects.annotate(
    <b>nlikes=Count('likes')</b>
).filter(
    <b>nlikes__gt=10</b>
)

截至 , we can replace the .annotate(…) with .alias() [Django-doc]

from django.db.models import Count

Post.objects.alias(
    <b>nlikes=Count('likes')</b>
).filter(
    <b>nlikes__gt=10</b>
)