Django查询与order_by,distinct和限制在Postgresql [英] Django query with order_by, distinct and limit on Postgresql

查看:209
本文介绍了Django查询与order_by,distinct和限制在Postgresql的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下内容:

class Product(models.Model):
    name = models.CharField(max_length=255)

class Action(models.Model):
    product = models.ForeignKey(Product)
    created_at = models.DateTimeField(auto_now_add=True)

我想检索由created_at DESC订购的10个最新动作,包含不同的产品。

I would like to retrieve the 10 most recent actions ordered by created_at DESC with distinct products.

以下是接近结果但仍然错过了排序:

The following is close to the result but still misses the ordering:

Action.objects.all().order_by('product_id').distinct('product_id')[:10]


推荐答案

您的解决方案似乎正在尝试做太多事情。它还将导致2个单独的SQL查询。这可以正常工作,只需一个查询:

Your solution seems like it's trying to do too much. It will also result in 2 separate SQL queries. This would work fine and with only a single query:

action_ids = Action.objects.order_by('product_id', '-created_at')\
    .distinct('product_id').values_list('id', flat=True)

result = Action.objects.filter(id__in=action_ids)\
    .order_by('-created_at')[:10]

这篇关于Django查询与order_by,distinct和限制在Postgresql的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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