django 在 select_related 字段上注释

django annotate on select_related field

我的简化模型:

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()

我需要将两个字段相乘存储在其他字段中,即 sum。为什么 Cart.objects.select_related('product__price').annotate(sum=F('product__price__value') * F('qnt')) returns 什么都没有?

F('') 替换为 F('value') returns 错误

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

您尝试将整数字段与小数字段相乘。因此,它发生错误。你可以试试这个

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