models.py:
class Post(models.Model):
author = models.ForeignKey('User')
text = models.TextField(max_length=320)
created_date = models.DateTimeField(default=timezone.now)
class Likes(models.Model):
post = models.ForeignKey('Post')
liker = models.ForeignKey('User')
created_date = models.DateTimeField(default=timezone.now)
class Meta:
unique_together = ('post', 'liker')
我想获得他们喜欢的最新帖子超过70个。如何用django orm编写该查询集?
答案 0 :(得分:3)
您需要注释喜欢的数量,然后过滤
Post.objects.annotate(num_likes=Count('likes')).filter(num_likes__gt=70).order_by('-created_date')
答案 1 :(得分:0)
你可以像这个例子那样做QV。
qv = Likes.objects.filter(liker__gt = 70).all()
out = Post.objects.filter(id__in=qv).order_by('-created_at')