用通用外键(django)对查询进行排序?

编程入门 行业动态 更新时间:2024-10-22 23:06:35
本文介绍了用通用外键(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)对查询进行排序?

本文发布于:2023-10-15 02:50:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1493028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:django

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!