Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use correct field name in forward many-to-many fields #39

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/zeal/patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,10 @@ def parser(context: QuerysetContext) -> QuerySource:
manager = context["args"][0]
model = manager.instance.__class__
related_model = manager.target_field.related_model
field_name = manager.prefetch_cache_name if rel.related_name else None
is_reverse = context["manager_call_args"]["reverse"]
field_name = (
rel.related_name if is_reverse else manager.prefetch_cache_name
)

model, field_name = parse_related_parts(
model, field_name, related_model
Expand Down
14 changes: 14 additions & 0 deletions tests/test_nplusones.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,20 @@ def test_no_false_positive_when_loading_single_object_reverse_many_to_many():
assert len(ctx.captured_queries) == 2


def test_detects_nplusone_in_forward_many_to_many_with_no_related_name():
[user_1, user_2] = UserFactory.create_batch(2)
user_1.blocked.add(user_2)
user_2.blocked.add(user_1)
with pytest.raises(
NPlusOneError, match=re.escape("N+1 detected on social.User.blocked")
):
for user in User.objects.all():
_ = list(user.blocked.all())

for user in User.objects.prefetch_related("blocked").all():
_ = list(user.blocked.all())


def test_detects_nplusone_in_reverse_many_to_many_with_no_related_name():
[user_1, user_2] = UserFactory.create_batch(2)
user_1.blocked.add(user_2)
Expand Down