gpt4 book ai didi

python - 属性错误 : 'CombinedExpression' object has no attribute 'default_alias'

转载 作者:行者123 更新时间:2023-12-05 08:40:19 27 4
gpt4 key购买 nike

当尝试减去两个不同的列时,出现此错误:

>>> Product.objects.annotate(Sum('producttransactiondetails__purchase_quantity') - Sum('producttransactiondetails__sales_quantity'))
Traceback (most recent call last):
File "/usr/lib/python3.6/code.py", line 91, in runcode
exec(code, self.locals)
File "<console>", line 1, in <module>
File "/home/....env/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/.....env/lib/python3.6/site-packages/django/db/models/query.py", line 1032, in annotate
if arg.default_alias in kwargs:
AttributeError: 'CombinedExpression' object has no attribute 'default_alias'

模型如下:

class ProductTransactionDetails(models.Model):
product = models.ForeignKey(Product, on_delete=models.PROTECT)
product_purchase = models.ForeignKey(ProductTransaction, on_delete=models.PROTECT)
purchase_quantity = models.PositiveIntegerField(default=0)
sales_quantity = models.PositiveIntegerField(default=0)
discount = models.DecimalField(max_digits=20, decimal_places=2)
product_price = models.DecimalField(max_digits=20, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Product(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE)
name = models.CharField(max_length=1000, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

最佳答案

您还没有为组合表达式分配列名

annotate() 子句的输出是一个QuerySet;此 QuerySet 可以使用任何其他 QuerySet 操作进行修改。所以每个值都需要在一列中,并且每一列都需要一个名称​​(您忘记添加了)

Product.objects.annotate(in_stock_quantity=Sum('producttransactiondetails__purchase_quantity') - Sum('producttransactiondetails__sales_quantity'))

注意这里的in_stock_quantity=

关于python - 属性错误 : 'CombinedExpression' object has no attribute 'default_alias' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56290399/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com