Fix HistoricForeignKey when used together with prefetch_related() #1159
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
This fixes behaviour of
HistoricForeignKey
when used together withprefetch_related()
.The following is sufficient to reproduce the bug:
Related Issue
#1152
Motivation and Context
Property
related_manager_cls
is defined inHistoricReverseManyToOneDescriptor
. This property returns a function call ofcreate_reverse_many_to_one_manager
function and passes itHistoricRelationModelManager
as an argument. However,create_reverse_many_to_one_manager
definesRelatedManager
, which subclasses the manager passed as an argument and returns thisRelatedManager
class.When
prefetch_related
is used,get_prefetch_queryset
method ofRelatedManager
is called.The problem lies in the fact that it bypasses
RelatedManager.get_queryset
method which does filtering to instance (_apply_rel_filters
) by callingsuper().get_queryset()
. But due to inheritance, it gets evaluated toHistoricRelationModelManager.get_queryset
which does the same filtering as well.This SQL is generated then (notice the
"poll_choice"."poll_id" = 1
condition):Removing
_apply_rel_filters
call fromHistoricRelationModelManager.get_queryset
solves this problem.On the other hand, since
create_reverse_many_to_one_manager
returnsRelatedManager
, rather thanHistoricRelationModelManager
, the only way to accessHistoricRelationModelManager.get_queryset
is by callingsuper().get_queryset()
fromRelatedManager
. This call can be found:RelatedManager.get_prefetch_queryset
where it is undesired,RelatedManager.get_queryset
where_apply_rel_filters
is called right aftersuper().get_queryset()
.Therefore, I believe it is safe to remove it.
How Has This Been Tested?
Added new tests.
Screenshots (if appropriate):
Types of changes
Checklist:
pre-commit run
command to format and lint.AUTHORS.rst
CHANGES.rst