postgresql Django不同,按不同列排序

ha5z0ras  于 2023-03-17  发布在  PostgreSQL
关注(0)|答案(2)|浏览(125)

我有这样的模型

class Product(models.Model):
        created_at = models.DateTimeField(default=timezone.now)
        cell = models.CharField(max_length=100, null=True)

现在我需要一个必须按创建日期和唯一单元格排序的查询集,类似于Product.objects.order_by('created_at').distinct('cell'),但我得到了一个sql错误。

django.db.utils.ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON ("apps_product"."cell")

应如何更改查询集以获得所需的结果?

jdzmm42g

jdzmm42g1#

根据错误消息,您应该尝试:
Product.objects.order_by('cell', '-created_at').distinct('cell')

q7solyqu

q7solyqu2#

如果没有子查询,当前无法执行此操作。存在一个开放的feature request,它允许以下查询:

qs = (
  Product.objects
  # deduplicate on "cell", keeping the most recently created record
  .order_by("cell", "-created_at").distinct("cell")
  # then order the result of the distinct subquery to get most recently created first
  .order_by("-created_at")
)

如果你现在尝试这个查询(从Django 4.1.7开始),它会失败,并显示和你发布的相同的错误消息。
正如功能请求下的注解所解释的那样,您可以尝试以下操作:

from django.db.models import Subquery
distinct = (
  Product.objects
  # deduplicate on "cell", keeping the most recently created record
  .order_by("cell", "-created_at").distinct("cell")
  .values("pk")
)
qs = (
  Product.objects
  .filter(pk__in=Subquery(distinct))
  # then order the result of the distinct subquery to get most recently created first
  .order_by("-created_at")
)

相关问题