#35442: N+1 queries from RelatedManager + only("pk") -------------------------------------+------------------------------------- Reporter: REGNIER Guillaume | Owner: nobody Type: Uncategorized | Status: new Component: Database layer | Version: 4.2 (models, ORM) | Severity: Normal | Resolution: Keywords: | Triage Stage: | Unreviewed Has patch: 0 | Needs documentation: 0 Needs tests: 0 | Patch needs improvement: 0 Easy pickings: 0 | UI/UX: 0 -------------------------------------+------------------------------------- Comment (by Natalia Bidart):
Hello Guillaume! I'm having a hard time understanding the goal of your code. I assume you have provided a simplified version to be used as a small example, which I appreciate, but with the information given, the proper way to fetch records from the database without generating N+1 queries would be: {{{#!python >>> from django.db import connection, reset_queries >>> reset_queries(); connection.queries [] >>> company = Company.objects.prefetch_related("employees").last() >>> for e in company.employees.all(): >>> print(e.pk) 7 8 9 10 >>> connection.queries [{'sql': 'SELECT "ticket_35442_company"."id", "ticket_35442_company"."name" FROM "ticket_35442_company" ORDER BY "ticket_35442_company"."id" DESC LIMIT 1', 'time': '0.002'}, {'sql': 'SELECT "ticket_35442_employee"."id", "ticket_35442_employee"."company_id" FROM "ticket_35442_employee" WHERE "ticket_35442_employee"."company_id" IN (5)', 'time': '0.001'}] }}} Or, my preferred (a single query): {{{#!python >>> for e in Employee.objects.filter(company=company).only("pk"): print(e.pk) 7 8 9 10 >>> connection.queries [{'sql': 'SELECT "ticket_35442_employee"."id" FROM "ticket_35442_employee" WHERE "ticket_35442_employee"."company_id" = 5', 'time': '0.000'}] }}} -- Ticket URL: <https://code.djangoproject.com/ticket/35442#comment:2> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/0107018f63b12707-5d234d84-62d7-435f-8a08-555681a05430-000000%40eu-central-1.amazonses.com.