在QuerySet中分配表别名

时间:2011-12-21 22:57:05

标签: django django-queryset

如何在Django中为QuerySet的主表分配别名?

  queryset = Price.objects
  queryset = queryset.extra(
    where = ['p1.created = (select max(p2.created) from products_price p2 where p2.product_id = p1.product_id)']
  )

我想将'p1'别名设置为Price主表,以便在子选择中使用它。

编辑:请注意,每个Produtc都有最新的价格。

1 个答案:

答案 0 :(得分:2)

您可以看到sql查询来执行下一步:

queryset = Price.objects.all()
print queryset.query

如果你知道第一个SQL查询。你可以更好地完成子查询。

虽然,我会做下一个:

price_max = Price.objects.all().order_by('-created')[0]
queryset = Price.objects.filter(created=price_max)

或者最好的:     https://docs.djangoproject.com/en/1.3/topics/db/aggregation/#generating-aggregates-over-a-queryset

from django.db.models import Max
price_max = Price.objects.aggregate((Max('created'))['created__max']
queryset = Price.objects.filter(created=price_max)