Django ORM字段查询某些计算时出错

Django ORM字段查询某些计算时出错,django,django-models,django-orm,Django,Django Models,Django Orm,这是我的购买模型: class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_by = models.ForeignKey( User, on_delete=models.SET_NULL, related_na

这是我的购买模型:

class Purchase(models.Model):
    amount = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0.00
    )
    entry_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        related_name='ledger_entry_by',
    )
这是我的消费模式:

class Consume(models.Model):
    amount = models.FloatField(default=1)
    consumed_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        related_name='consume_entry_for',
    )
我试图找出用户的消费量比他购买的多,消费量比他购买的少

这是我对此的查询:

purchase_vs_consume = User.objects.annotate(
            purchase_vs_consume=Coalesce(Sum('ledger_entry_for__amount'), Value(0))  - Coalesce(Sum('consume_entry_for__amount'), Value(0))
        )
它抛出以下错误:

Expression contains mixed types: DecimalField, FloatField. You must set output_field
QuerySet.annotate() received non-expression(s): <django.db.models.fields.FloatField>.
后来我的问题是:

purchase_vs_consume = User.objects.annotate(
            purchase_vs_consume=Coalesce(Sum('ledger_entry_for__amount'), Value(0))  - Coalesce(Sum('consume_entry_for__amount'), Value(0)), output_field=FloatField()
        )
它抛出以下错误:

Expression contains mixed types: DecimalField, FloatField. You must set output_field
QuerySet.annotate() received non-expression(s): <django.db.models.fields.FloatField>.
QuerySet.annotate()接收到非表达式:。
我不明白这是怎么回事

我想要:

例如,一个用户购买了500美元,他消费了550美元,也就是说,他需要再支付50美元

另一个用户购买了440美元,但他消费了400美元,也就是说,您将获得40美元的退款。

另一个用户示例可以是:用户没有购买任何东西,但他消费了300美元,因此他需要支付300美元

我试图达到以上的计算,但它火我一个错误

有人能帮我做到这一点吗

User.objects.annotate(purchase_vs_consume=Coalesce(Sum('ledger_entry_by__amount'), Value(0), output_field=FloatField()) - Coalesce(Sum('consume_entry_for__amount'), Value(0), output_field=FloatField())).values('purchase_vs_consume')
请更新您的查询。在每个模型中使用两种不同类型的字段并进行计算。因此,当在内部进行聚合时,必须传递一个
output\u字段
,以便在相同的数据类型上进行计算。 在使用\u条目\u的情况下,不需要传递output\u字段,因为该字段已经是一个FloatField,因此查询将在不传递该字段的情况下工作