是否可以做这样的事情?
outputs = {"total_kgs": "kgs"}
Model.objects.all().aggregate(**outputs)
取代:
Model.objects.all().aggregate(total_kgs="kgs")
现在我得到了:
AttributeError:'str'对象没有属性'resolve_expression'
以下是我目前正在尝试做的事情:
类InventoryManager(经理):
def lookup(self, operators, fields, status, labels=None):
outputs = {}
if status == "unsold":
operators.update({"status__lt": choices.SOLD})
q = [Q(**operators)]
for field in fields:
label = labels.pop(0) if labels else "{}_total".format(field)
outputs.update({label: field})
return self.model.objects.filter(reduce(operator.and_, q)).aggregate(**outputs)
def total_kgs(self, status='unsold'):
operators = {"supplier__market__weights": "KGS"}
operators.update({'supplier__market__currency_code':"INR"})
return self.lookup(operators, ["weight", "invoice_value"], status)
相关模型数据:
class Purchase(models.Model):
invoice = models.CharField(max_length=24, unique=True)
lbs = models.DecimalField(decimal_places=4, max_digits=48, blank=True, null=True)
kgs = models.DecimalField(decimal_places=4, max_digits=48, blank=True, null=True)
invoice_value = models.DecimalField(decimal_places=4, max_digits=48, blank=True, null=True)
status = models.IntegerField(choices=choices.STATUS_CHOICES, default=choices.PENDING)
最终我想为每个查询做些什么:
self.model.objects.filter(reduce(operator.and_, q)).aggregate(total_weight=Coalesce(Sum("weight"), 0))
答案 0 :(得分:0)
所以whaddya知道。如果你插入正确的表达式,它就可以正常工作。再次感谢。
for field in fields:
label = labels.pop(0) if labels else "{}_total".format(field)
outputs.update({label: Coalesce(Sum(field), 0)})