我试图按每个Game
和最近的title
(帖子)排序模型update
而不返回重复项。
views.朋友
'recent_games': Game.objects.all().order_by('title', '-update__date_published').distinct('title')[:5],
查询上的独特方法完美无缺,但update__date_published
似乎不起作用。
models.朋友
模特 - 游戏
class Game(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
description = models.TextField()
date_published = models.DateTimeField(default=timezone.now)
cover = models.ImageField(upload_to='game_covers')
cover_display = models.ImageField(default='default.png', upload_to='game_displays')
developer = models.CharField(max_length=100)
twitter = models.CharField(max_length=50, default='')
reddit = models.CharField(max_length=50, default='')
platform = models.ManyToManyField(Platform)
def __str__(self):
return self.title
模型 - 更新
class Update(models.Model):
author = models.ForeignKey(User, models.SET_NULL, blank=True, null=True,) # If user is deleted keep all updates by said user
article_title = models.CharField(max_length=100, help_text="Use format: Release Notes for MM/DD/YYYY")
content = models.TextField(help_text="Try to stick with a central theme for your game. Bullet points is the preferred method of posting updates.")
date_published = models.DateTimeField(db_index=True, default=timezone.now, help_text="Use date of update not current time")
game = models.ForeignKey(Game, on_delete=models.CASCADE)
article_image = models.ImageField(default='/media/default.png', upload_to='article_pics', help_text="")
platform = ChainedManyToManyField(
Platform,
horizontal=True,
chained_field="game",
chained_model_field="game",
help_text="You must select a game first to autopopulate this field. You can select multiple platforms using Ctrl & Select (PC) or ⌘ & Select (Mac).")
请参阅distinct
参考Examples (those after the first will only work on PostgreSQL)
请参阅此反向查询 - See this one for - update__date_published
示例 -
Entry.objects.order_by('blog__name', 'mod_date').distinct('blog__name', 'mod_date')
您的查询-
Game.objects.order_by('title', '-update__date_published').distinct('title')[:5]
你说:
-update__date_published似乎不起作用,因为游戏只按字母顺序返回。
原因是第一个order_by
场是title
;如果你有几个相同的-update__date_published
s,那么二级订单字段title
才会启动,你不会因为distinct()
。
如果你想要Game
对象按最新更新而不是它们的标题排序,从排序中省略title
似乎是明显的解决方案,直到你得到ProgrammingError
DISTINCT ON field
在field
条款的开头需要ORDER BY
。
通过最新更新对游戏进行排序的真正解决方案是:
games = (Game.objects
.annotate(max_date=Max('update__date_published'))
.order_by('-update__date_published'))[:5]
这里最可能的误解是你的orm查询中的连接。它们实际上是懒惰加载,所以date_published
字段尚不可用,但你正试图对它进行排序。您需要使用select_related
方法将fk关系作为连接加载。
'recent_games': Game.objects.select_related('update').all().order_by('title', '-update__date_published').distinct('title')[:5]