【发布时间】: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