【问题标题】:Django ORM: Min('field',filter=...) causes TypeError: can only concatenate list (not "tuple") to listDjango ORM: Min('field',filter=...) 导致 TypeError: can only concatenate list (not "tuple") to list
【发布时间】:2019-05-26 07:27:40
【问题描述】:

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

你知道该怎么做吗?

【问题讨论】:

    标签: python sql django postgresql django-orm


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      基本上你应该将django.db.models.query_utls.Q 对象作为filter 参数而不是过滤的查询集传递给Min

      locations_annotated = Location.objects.all().annotate(
                  min_price=Min('ticket__price', filter=Q(something)))
      

      请注意,something 中的所有过滤器都应在前面加上 ticket__ 前缀

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-02
        • 2014-07-31
        • 2022-10-23
        • 2020-09-25
        • 2021-04-26
        • 1970-01-01
        • 2022-11-01
        • 2020-11-21
        相关资源
        最近更新 更多