﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31666	Combine prefetch_related queries for FK's to the same target model	Adam Johnson	nobody	"If you have a source model with two or more FK's to the same target model, `prefetch_related()` for those FK's could do a single query rather than several. For models with duplicate targets in different FK's, this would also reduce transferred data and duplicate objects in memory.

For example:

{{{
from django.db import models


class Author(models.Model):
    pass


class Book(models.Model):
    author1 = models.ForeignKey(Author, on_delete=models.DO_NOTHING, related_name='+')
    author2 = models.ForeignKey(Author, on_delete=models.DO_NOTHING, related_name='+')
}}}

If I create some authors and fetch everything, the same author is represented by two objects because they were fetched in different queries:

{{{
In [1]: from example.core.models import Author, Book

In [2]: a1 = Author.objects.create()

In [3]: a2 = Author.objects.create()

In [4]: a3 = Author.objects.create()

In [5]: b1 = Book.objects.create(author1=a1, author2=a2)

In [6]: b2 = Book.objects.create(author1=a2, author2=a3)

In [7]: bs = Book.objects.prefetch_related('author1', 'author2')

In [8]: bs[0].author1
Out[8]: <Author: Author object (1)>

In [9]: bs[0].author2
Out[9]: <Author: Author object (2)>

In [10]: bs[1].author1
Out[10]: <Author: Author object (2)>

In [11]: bs[0].author2 is bs[1].author1
Out[11]: False
}}}"	Cleanup/optimization	closed	Database layer (models, ORM)	dev	Normal	wontfix			Unreviewed	0	0	0	0	0	0
