阅读关于该主题的 django docs 它表示需要使用聚合API来计算它们不:
Django的数据库聚合API不不能使用GenericRelation。 [...]现在,如果您需要关于通用关系的聚合,则需要在不使用聚合API的情况下进行计算。
我可以想到的唯一方法是遍历我的查询集,生成一个包含 content_type 和 object_id 的每个项目,然后运行第二个查询器在注释模型过滤由这个列表的 content_type 和 object_id ...通过计数对对象进行排序,然后通过为每个注释拉 content_object 来重新创建一个新的查询器。
这似乎是错误的,我甚至不知道如何拉开它。
想法?有人必须这样做。
我发现这篇文章在线,但它需要我手写SQL - 这是真的有必要吗?
解决方案您在问题链接的博文中发现的方式是我做的方式(而且,几乎是我本周早些时候在自己的一个项目中所做的那样)
I am using Django's comment framework which utilizes generic foreign keys.
Question: How do I sort a given model's queryset by their comment count using the generic foreign key lookup?Reading the django docs on the subject it says one needs to calculate them not using the aggregation API:
Django's database aggregation API doesn't work with a GenericRelation. [...] For now, if you need aggregates on generic relations, you'll need to calculate them without using the aggregation API.
The only way I can think of, though, would be to iterate through my queryset, generate a list with content_type and object_id's for each item, then run a second queryset on the Comment model filtering by this list of content_type and object_id ... sort the objects by the count, then re-create a new queryset in this order by pulling the content_object for each comment ...
This just seems wrong and I'm not even sure how to pull it off.
Ideas? Someone must have done this before.
I found this post online but it requires me handwriting SQL -- is that really necessary ?
解决方案The way you found in the blog post linked in your question is the way I'd do it (and, indeed, pretty much the way I did it in one of my own projects earlier this week)
更多推荐
用通用外键(django)对查询进行排序?
发布评论