使用ForeignKey按order_by排序,并且不能正常工作

问题描述 投票:0回答:3

我试图按每个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).")
django django-queryset django-orm
3个回答
0
投票

请参阅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]

0
投票

你说:

-update__date_published似乎不起作用,因为游戏只按字母顺序返回。

原因是第一个order_by场是title;如果你有几个相同的-update__date_publisheds,那么二级订单字段title才会启动,你不会因为distinct()

如果你想要Game对象按最新更新而不是它们的标题排序,从排序中省略title似乎是明显的解决方案,直到你得到ProgrammingError DISTINCT ON fieldfield条款的开头需要ORDER BY

通过最新更新对游戏进行排序的真正解决方案是:

games = (Game.objects
    .annotate(max_date=Max('update__date_published'))
    .order_by('-update__date_published'))[:5]

-1
投票

这里最可能的误解是你的orm查询中的连接。它们实际上是懒惰加载,所以date_published字段尚不可用,但你正试图对它进行排序。您需要使用select_related方法将fk关系作为连接加载。

'recent_games': Game.objects.select_related('update').all().order_by('title', '-update__date_published').distinct('title')[:5]

© www.soinside.com 2019 - 2024. All rights reserved.