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 for None values in prefetch when fk_id==0 #1055

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ Changelog

0.18
====
0.18.3
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add in 0.19.2

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thank you

------
Fixed
^^^^^
- Fix for prefetch_related with foreign key id == 0.

0.18.2
------
Fixed
Expand Down
7 changes: 7 additions & 0 deletions tests/test_relations.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,13 @@ async def test_prefetch_related_fk(self):
event2 = await Event.filter(name="Test").prefetch_related("tournament")
self.assertEqual(event2[0].tournament, tournament)

async def test_prefetch_related_fk_id_zero(self):
tournament = await Tournament.create(id=0, name="New Tournament")
await Event.create(name="Test", tournament_id=tournament.id)

event2 = await Event.filter(name="Test").prefetch_related("tournament")
self.assertEqual(event2[0].tournament, tournament)

async def test_prefetch_related_rfk(self):
tournament = await Tournament.create(name="New Tournament")
event = await Event.create(name="Test", tournament_id=tournament.id)
Expand Down
2 changes: 1 addition & 1 deletion tortoise/backends/base/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ async def _prefetch_direct_relation(
related_objects_for_fetch: Dict[str, list] = {}
relation_key_field = f"{field}_id"
for instance in instance_list:
if getattr(instance, relation_key_field):
if getattr(instance, relation_key_field) != None:
konchunas marked this conversation as resolved.
Show resolved Hide resolved
key = cast(RelationalField, instance._meta.fields_map[field]).to_field
if key not in related_objects_for_fetch:
related_objects_for_fetch[key] = []
Expand Down