[英]Django - sort QuerySet by backwards related model's field
I have the following (simplified) models: 我有以下(简化的)模型:
class Post(models.Model):
title=models.CharField(max_length=500)
class Recommendation(models.Model):
post=models.ForeignKey(Post)
submit_time=models.DateTimeField(auto_now_add=True)
And I want to get the list of distinct Posts
ordered by Recommendation's
submit time. 我想获得按
Recommendation's
提交时间排序的不同Posts
列表。 The first way I tried was the straighforward: 我尝试的第一种方法是直率的:
Post.objects.order_by('recommendation__submit_time').distinct()
But surprisingly this gave a QuerySet with duplicate Post objects. 但是令人惊讶的是,这给了带有重复Post对象的QuerySet。 Turns out the rows are actually different because Django adds extra columns for the ordering, but does not return them in the results .
事实证明行实际上是不同的,因为Django为排序添加了额外的列,但没有在结果中返回它们 。
Looking around I found a couple answers on SO, including to use aggregation instead of ordering: 环顾四周,我在SO上找到了两个答案,包括使用聚合而不是排序:
Post.objects.all().annotate(Max('recommendation__submit_time')).order_by('recommendation__submit_time__max')
Or to de-normalize the model and add a last_recommended_time
field to Post
. 或对模型进行反规范化,然后在
Post
添加一个last_recommended_time
字段。
Most of the questions/answers already in SO are a couple years old, so I was wondering if there's a more idiomatic and straightforward way to do this than those suggested hacks. SO中已经存在的大多数问题/答案都已经存在了两年之久,所以我想知道是否有比建议的骇客更惯用和直接的方法来做到这一点。
EDIT: Just thought I made it clear: The solutions listed above do work and I'm using them (albeit not in production). 编辑:只是以为我已经明确了:上面列出的解决方案确实有效,我正在使用它们(尽管不在生产中)。 I'm just interested in better solutions to this issue.
我只是想为这个问题提供更好的解决方案。
Have you thought about using raw sql 您是否考虑过使用原始SQL
Post.objects.raw("""
SELECT DISTINCT post FROM
(SELECT appname_post.post_id AS post, appname_recommendation.submit_time
FROM appname_post
INNER JOIN appname_recommendation
ON appname_post.post_id = appname_recommendation.post_id
ORDER_BY appname_recommendation.submit_time)
""")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.