首页 > 解决方案 > Django ORM: Min('field',filter=...) 导致 TypeError: can only concatenate list (not "tuple") to list

问题描述

有一个模型Location可以有许多Ticket对象(使用ForeignKey)。

Ticket模型的price字段是DecimalField.

现在我已经过滤了对象的 QuerySet Ticket,我想获取Location对象的 QuerySet 并注释值,这是FILTERED QuerySet 中所有对象min_price的最低价格。Ticket

例如:

tickets = Ticket.objects.filter(something)

locations = Location.objects.all().annotate(min_price=<minimal price from tickets having this location>)

我尝试了什么:

locations_annotated = Location.objects.all().annotate(
            min_price=Min('tickets__min_price', filter=tickets))

这行不通。当我尝试从中获取第一个元素时locations_annotated,调试器返回:

TypeError: can only concatenate list (not "tuple") to list 

你知道该怎么做吗?

标签: pythonsqldjangopostgresqldjango-orm

解决方案


我认为注释没有正确使用。请试试,

locations_annotated = Location.objects.annotate(
        min_price=Min('tickets__min_price', filter=tickets)

推荐阅读