Django 1.8.当我们在值中使用ID字段并在Django中使用注释操作时,将忽略结果SQL Query中的另一个字



我想将Django从1.7.11更新为1.11.18。但是我发现了一个问题。Django为不同的Django版本制作了不同的SQL-Queries。例如。我有一个查询:

Account.objects
       .values('id', 'name', invoice__payment__payment_gateway')
       .annotate(
         pay_paid=Sum('invoice__payment__amount'),
         pay_refunded=Sum('invoice__payment__amount_refunded')
       )
       .order_by('-name', )

sql-Query for Django 1.7.11:

SELECT `member_account`.`id`, 
       `member_account`.`name`, 
       `member_payment`.`payment_gateway`, 
       SUM(`member_payment`.`amount_refunded`) AS `pay_refunded`, 
       SUM(`member_payment`.`amount`) AS `pay_paid` 
FROM `member_account` 
  LEFT OUTER JOIN `member_invoice` ON ( `member_account`.`id` = `member_invoice`.`account_id` ) 
  LEFT OUTER JOIN `member_payment` ON ( `member_invoice`.`id` = `member_payment`.`invoice_id` ) 
GROUP BY `member_account`.`id`, `member_account`.`name`, `member_payment`.`payment_gateway` 
ORDER BY `member_account`.`name` DESC

请注意GROUP BY部分。有3个字段: ID 名称 payment_gateway

,但我们有django 1.8.19的sql-Query:

SELECT `member_account`.`id`, 
       `member_account`.`name`, 
       `member_payment`.`payment_gateway`, 
       SUM(`member_payment`.`amount_refunded`) AS `pay_refunded`, 
       SUM(`member_payment`.`amount`) AS `pay_paid` 
FROM `member_account` 
  LEFT OUTER JOIN `member_invoice` ON ( `member_account`.`id` = `member_invoice`.`account_id` ) 
  LEFT OUTER JOIN `member_payment` ON ( `member_invoice`.`id` = `member_payment`.`invoice_id` ) 
GROUP BY `member_account`.`id` 
ORDER BY `member_account`.`name` DESC

,我们在GROUP BY部分中只有一个字段。为什么我们只有一个 id 字段?这是主要问题。

但是,当我删除 ID values的字段django 1.8 1.8制造有效的sql-Query:

SELECT `member_account`.`name`, 
       `member_payment`.`payment_gateway`, 
       SUM(`member_payment`.`amount_refunded`) AS `pay_refunded`, 
       SUM(`member_payment`.`amount`) AS `pay_paid` 
FROM `member_account` 
  LEFT OUTER JOIN `member_invoice` ON ( `member_account`.`id` = `member_invoice`.`account_id` ) 
  LEFT OUTER JOIN `member_payment` ON ( `member_invoice`.`id` = `member_payment`.`invoice_id` ) 
GROUP BY `member_account`.`name`, `member_payment`.`payment_gateway` 
ORDER BY `member_account`.`name` DESC

最近的Django版本似乎省略了group by子句的冗余字段。如果您按表中的唯一字段进行分组,则该表由任何其他字段分组没有意义。这肯定解释了member_account.name的省略,如果您在查询中具有唯一的member_account.id,这是多余的。

payment_gateway 可能是如此,如果您对每个帐户只有一个payment_gateway的效果有限制。如果帐户可以有几个付款网关,那么我没有立即说明为什么Django认为该字段是为了group_by的目的。

如果您显示相关模型的定义,我们可能能够告诉您更多。

相关内容

  • 没有找到相关文章

最新更新