我有一个Django模型 Document ,它可以有 Vote 对象指向它 . Vote 上有一个名为 score 的整数字段 .
Document
Vote
score
我想根据指向文档的 score=1 的 Vote 对象的数量来订购文档的查询集 . 即,具有最多正投票的文档应该是查询集中的第一个 .
score=1
Django有可能吗?怎么样?
这是一个注释工作 .
from django.db.models import Count Document.objects.filter(score=1).annotate( positive_votes=Count('vote__count')).order_by('positive_votes')
Edit
没有过滤就没有办法做到这一点,因为这是底层数据库操作的工作方式 . 但是,一种不太好的方法是对原始中未包含的所有文档进行单独查询,并将两个查询集链接在一起:
positive_docs = <query from above> other_docs = Document.objects.exclude(id__in=positive_docs) all_docs = itertools.chain(positive_docs, other_docs)
只要你没有数以百万计的文档,这就可以工作,但会破坏像分页这样的东西 .
我这样做了(在 QuerySet 模型上):
QuerySet
def order_by_score(self): q = django.db.models.Q(ratings__score=1) documents_with_one_positive_rating = self.filter(q) # Annotation sees only # the positive ratings documents_without_one_positive_rating = self.filter(~q) return (documents_with_one_positive_rating | documents_without_one_positive_rating).annotate( db_score=django.db.models.Count('ratings') ).order_by('-db_score')
优点是它仍然显示没有正面评级的文件 .
2 回答
这是一个注释工作 .
Edit
没有过滤就没有办法做到这一点,因为这是底层数据库操作的工作方式 . 但是,一种不太好的方法是对原始中未包含的所有文档进行单独查询,并将两个查询集链接在一起:
只要你没有数以百万计的文档,这就可以工作,但会破坏像分页这样的东西 .
我这样做了(在
QuerySet
模型上):优点是它仍然显示没有正面评级的文件 .