我有以下模型
class Article(models.Model):
title = models.CharField(max_length=255, db_index=True)
slug = UniqueSlugField(prepopulate_from='title', unique=True)
favorited = models.ManyToManyField(to=User, blank=True)
tags = TaggableManager()
...
class Vote(models.Model):
article = models.ForeignKey(to=Article)
voter = models.ForeignKey(to=User, related_name='voter')
timestamp = models.DateTimeField(auto_now_add=True)
...我使用下面这行代码以降序方式获取所选标签的热门文章
Vote.objects.filter(tags__in=[tag]).annotate(num_articles=Count('article')).order_by('-num_articles')
如何在Vote模型的基础上,通过Article.favorited的以下字段建立orm查询,以获取热门文章?
谢谢,
苏尔坦
发布于 2012-05-17 23:20:02
为什么要通过Vote模型获取“热门文章”?当您运行查询时,您最终得到了一个Votes的查询集。然后,您必须发出额外的查询来从中获取Articles。
您应该使用:
Article.objects.filter(tags=tag).annotate(vote_count=Count('vote')).order_by('-vote_count')然后,您就有了一个适当的Article查询集,就可以开始工作了。
如果您想要收藏,可以修改上面的代码以使用user而不是vote
Article.objects.filter(tags=tag).annotate(favorite_count=Count('user')).order_by('-favorite_count')发布于 2012-05-17 23:24:00
使用join
Article.objects.filter(favorited__in=[...]).annotate(
vc=models.Count('vote')).order_by('-vc')或者通常更快(连接更少),但更复杂,更有限(不再是QuerySet,但通常不是大问题)子查询版本
qs = Article.objects.filter(favorited__in=[...])
top_votes = Vote.objects.filter(article__in=qs).values('article').annotate(
vc=models.Count('pk')).values_list('article', 'vc').order_by('-vc')
# normally you may only want Top N
top_n_pks = tuple(pk for pk, vc in top_votes[:N])
tops = sorted(Article.objects.filter(pk__in=top_n_pks).order_by(),
key=lambda x: top_n_pks.index(x.pk))https://stackoverflow.com/questions/10638316
复制相似问题