有一个模型Location
可以有很多Ticket
对象(使用 ForeignKey
)。
Ticket
模型具有price
字段,这是一个DecimalField
。
现在我已经过滤了Ticket
对象的查询集,我想获取Location
对象的查询集并注释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
你知道该怎么做吗?
django.db.models.query_utls.Q
对象作为参数传递filter
而不是过滤的查询集传递到Min
:
locations_annotated = Location.objects.all().annotate(
min_price=Min('ticket__price', filter=Q(something)))
请注意,something
中的所有筛选器都应以前缀ticket__
我认为注释没有正确使用。请尝试,
locations_annotated = Location.objects.annotate(
min_price=Min('tickets__min_price', filter=tickets)