我有以下代码:
class Invoice(models.Model):
customer = models.ForeignKey(User, blank=True, null=True)
customer_name = models.CharField(max_length=50, blank=True, null=True)
email = models.CharField(max_length=100, blank=True, null=True)
#----------------------------------
invoices = Invoice.objects.raw("""
SELECT
`invoices`.`id`,
`invoices`.`customer_id`,
`invoices`.`customer_name`,
`invoices`.`email` AS `inv_email`,
`auth_user`.`username`,
`auth_user`.`email` AS `auth_email`,
COUNT('customer_id') AS `buy_count`
FROM `invoices`
LEFT JOIN `auth_user` ON `auth_user`.id = `invoices`.customer_id
GROUP BY `customer_id`, `invoices`.`email`
""", translations={'inv_email': 'email', 'auth_email': 'customer.email'})
但是,当我写invoices[i].customer
时,Django会为每个客户提出SQL请求。有办法在原始请求中将JOIN
映射到Django模型吗?或者这个SQL请求可以使用纯Django ORM来实现?