Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'CombinedExpression' object has no attribute 'default_alias'

Tags:

python

django

When trying to subtract two different columns, I got this error:

>>> 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'

Here are the models:

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)
like image 615
pyprism Avatar asked Nov 16 '25 11:11

pyprism


1 Answers

You have not assigned a column name to your combined expression.

The output of the annotate() clause is a QuerySet; this QuerySet can be modified using any other QuerySet operation. So every value needs to be in a column and every column needs a name (which you forgot to add)

Do

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

Mind the in_stock_quantity= here

like image 89
xxbinxx Avatar answered Nov 18 '25 13:11

xxbinxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!