Django merge makes excessive GROUP BY offers

I am doing very simple aggregation using Django ORM in MySQL, and it creates a GROUP BY that includes a data field, which is very large, and slows down the query more than 100 times.

Here is a simplified version of the model:

 class Document(models.Model): data = models.TextField() class Attachment(models.Model): document = models.ForeignKey(Document) 

And the request that I run:

 Document.objects.annotate(num_attachments=Count('attachment')) 

And the SQL output:

 SELECT `document_document`.`id`, `document_document`.`data`, COUNT(`document_attachment`.`id`) AS `num_attachments` FROM `document_document` LEFT OUTER JOIN `document_attachment` ON (`document_document`.`id` = `document_attachment`.`document_id`) GROUP BY `document_document`.`id`, `document_document`.`id`, `document_document`.`data` ORDER BY NULL 

Executing GROUP BY in a data field is not necessary and ridiculous. I can stop this by running values request:

 Document.objects.values('pk').annotate(num_attachments=Count('attachment')) 

But how can I get a real, annotated document request as a result?

+4
source share
1 answer

Karen Tracy, an explicit Django committer, confirmed that this is actually a bug in Django:

http://groups.google.com/group/django-users/browse_thread/thread/22d4d46c8646b2c4#

https://code.djangoproject.com/ticket/17144

+2
source

Source: https://habr.com/ru/post/1379225/


All Articles