Django ORM:Min('field',filter=...) 导致 TypeError: 只能连接列表(不是"tuple")到列表



有一个模型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)

最新更新