Django查询与order

编程入门 行业动态 更新时间:2024-10-27 21:13:08
本文介绍了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

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

发布评论

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

>www.elefans.com

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