Django 在查询集中指定表别名

Django 在查询集中指定表别名,django,django-queryset,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 main表,以便在子选择中使用它 编辑:请注意,每个产品UTC

如何将别名分配给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 main表,以便在子选择中使用它


编辑:请注意,每个产品UTC都有一个最新价格。

您可以查看sql查询以执行下一步操作:

queryset = Price.objects.all()
print queryset.query
price_max = Price.objects.all().order_by('-created')[0]
queryset = Price.objects.filter(created=price_max)
如果您知道第一个sql查询。您可以更好地执行子查询

尽管如此,我还是要做下一件事:

queryset = Price.objects.all()
print queryset.query
price_max = Price.objects.all().order_by('-created')[0]
queryset = Price.objects.filter(created=price_max)
或者最好的:


我想得到每个产品的最新价格(这是创建的最高价格)。这就是为什么我使用子查询和过滤器“where p2.product\u id=p1.product\u id”。是否有可能用聚合复制它?