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 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
3 changes: 2 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Fixed
- Fixed connection to `Oracle` database by adding database info to DBQ in connection string.
- Fixed ORA-01435 error while using `Oracle` database (#1155)
- Fixed processing of `ssl` option in MySQL connection string.
- Fix for prefetch_related with foreign key id == 0.

0.19.1
------
Expand Down Expand Up @@ -1265,4 +1266,4 @@ Docs/examples:

await Tournament.filter(
events__name__in=['1', '3']
).order_by('-events__participants__name').distinct()
).order_by('-events__participants__name').distinct()
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) is not None:
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