用通用外键(django)对查询进行排序? [英] Sort queryset by a generic foreign key (django)?

查看:220
本文介绍了用通用外键(django)对查询进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django的评论框架,它利用通用的外键。



问题:如何使用通用外键查找对其给定模型的查询集进行排序?



阅读关于该主题的 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)对查询进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆