Search code examples
djangoannotatedjango-select-related

django annotate on select_related field


My simplified models:

class Product(models.Model):
    name = models.CharField()

class Price(models.Model):
    product = models.OneToOneField('Product', primary_key=True)
    value = models.DecimalField()

class Cart(models.Model):
    product = models.ForeignKey('Product')
    qnt =  models.IntegerField()

I need multiplication of two fields get stored in other field namely sum . Why does Cart.objects.select_related('product__price').annotate(sum=F('product__price__value') * F('qnt')) returns nothing?

Replacing F('') to F('value') returns error

Cannot resolve keyword 'value' into field. Choices are: cart_id, id, product, product_id, qnt


Solution

  • You try to multiply Integer Field with Decimal Field. So, it occurs an error. You can try this

    from django.db.models import ExpressionWrapper, F, DecimalField
    
    
    Cart.objects.select_related('product__price').annotate(
        sum= ExpressionWrapper(
            F('product__price__value') * F('qnt'), output_field=DecimalField()))
    

    If the fields that you’re combining are of different types you’ll need to tell Django what kind of field will be returned. Since F() does not directly support output_field you will need to wrap the expression with ExpressionWrapper