【发布时间】:2021-07-14 20:54:54
【问题描述】:
我有以下型号:
class Customer(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField(max_length = 255, default='example@example.com')
authorized_credit = models.IntegerField(default=0)
balance = models.IntegerField(default=0)
class Transaction(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
payment_amount = models.IntegerField(default=0) #can be 0 or have value
exit_amount = models.IntegerField(default=0) #can be 0 or have value
transaction_date = models.DateField()
我想查询获取所有客户信息和最后付款日期。
我在 postgres 中有这个查询是正确的,只是我需要:
select e.*, max(l.transaction_date) as last_date_payment
from app_customer as e
left join app_transaction as l
on e.id = l.customer_id and l.payment_amount != 0
group by e.id
order by e.id
但我需要在 django 中使用此查询作为序列化程序。我尝试这样做,但返回其他查询
In Python:
print(Customer.objects.filter(transaction__isnull=True).order_by('id').query)
>>> SELECT app_customer.id, app_customer.name, app_customer.email, app_customer.balance FROM app_customer
LEFT OUTER JOIN app_transaction
ON (app_customer.id = app_transaction.customer_id)
WHERE app_transaction.id IS NULL
ORDER BY app_customer.id ASC
但我需要的是这一行
【问题讨论】:
-
嗨,欢迎来到堆栈溢出。我会尽力解决你的问题。
标签: python python-3.x django django-models django-rest-framework