【发布时间】:2020-11-20 07:43:03
【问题描述】:
我有一个类似的 Django 模型
# app/models.py
class tbl_invoice(models.Model):
invoice_id = models.IntegerField(blank=True, null=True)
client_id = models.ForeignKey(tbl_customer, on_delete=models.CASCADE)
invoice_number = models.IntegerField(blank=True, null=True)
date = models.DateField(blank=True, null=True)
amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
paid_amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
balance = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
date_of_payment = models.DateField(blank=True, null=True)
status = models.CharField(max_length=50, default='', blank=True, null=True)
我有另一个保存付款记录的视图,我想根据用户输入的差异将status 更新为 Paid 或 Unpaid金额和balance 是否为0
目前,这就是我所做的
#app/views.py
if form.is_valid():
post = form.save(commit=False)
# rest of the logic goes here
post.save()
# this data is saved in another model, after that I update invoice model
tbl_invoice.objects.filter(invoice_id=someIdHere).update(paid_amount=F('paid_amount')+post.amount,
date_of_payment=post.date, balance=F('balance')-post.amount,
status=Case(
When(balance=F('balance')-post.amount==0, then=Value("Paid")),
When(balance=F('balance')-post.amount!=0, then=Value("Unpaid")),
))
此查询将status 更新为空白。
但是,仅使用 F 表达式来更新 amount 和 balance 工作正常
tbl_invoice.objects.filter(invoice_id=someIdHere).update(paid_amount=F('paid_amount')+post.amount,
date_of_payment=post.date, balance=F('balance')-post.amount
以上语句运行良好
我肯定犯了一些我无法弄清楚的明显错误。
如何将F 表达式与Case 一起使用??
【问题讨论】:
-
您错误地使用了
When()。您只需要在 when 中使用不带F()的字段名称。更改为balance=0并为非 0 值设置默认值。尝试阅读docs.djangoproject.com/en/3.1/ref/models/…
标签: django django-models orm