【问题标题】:Adding an annotation to django queryset to be used by django_tables2向 django_tables2 使用的 django 查询集添加注释
【发布时间】:2020-11-24 05:53:22
【问题描述】:

我有一个模型(在其他字段中)有一个项目当前价格的值和一个项目通常价格的值。我想包括一个节省百分比的字段。我已经使用@property 完成了这项工作:

@property
def percSaving(self):
    aval = self.stickerprice
    bval = self.currentprice
    if self.stickerprice > 0:
        return  "%0.2f" % ((aval-bval)/aval*100) + "%"
    elif self.currentprice == 0:
        return "Always Free"
    else:
        return "100% OFF"

这行得通,我可以将此列添加到我的 django_table2 表中:

percSaving = tables.Column(verbose_name='% Saving')

超级简单,一切都很好。但是,我无法按此列排序。这是因为它不是查询集中的数据列之一。所以我一直在尝试对查询集进行注释,以允许我通过注释尝试对这个queryset api reference page 进行排序,并产生了这个:

annoed = products.objects.annotate(percSaving=((stickerprice)-(currentprice))/(stickerprice))

但是这给了我一个“name 'stickerprice' is not defined”的错误,我认为这可能是因为没有在字段名称周围使用逗号,但我尝试了这个并得到了一个错误说“unsupported operand type(s) for -: 'str' and 'str'” - 基本上使用反逗号强制它将字段名称视为字符串。

我做错了什么?如何注释查询集以允许按上面定义的列排序!

【问题讨论】:

    标签: django django-queryset django-tables2


    【解决方案1】:

    是的,你可以。通过提供更多的代码,如模型等。我只能提出一些一般性的建议。 您应该使用 F 函数在查询中进行计算,例如:

        annoed = products.objects.annotate(
            percSaving=((F("stickerprice") - F("currentprice")) / F("stickerprice"))
        )
    

    还要检查How to make sum query with type casting and calculation in django views?,它还提供了一些类型转换提示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-08
      • 2019-12-30
      • 2016-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 2019-03-20
      相关资源
      最近更新 更多