Skip to content
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
2 changes: 2 additions & 0 deletions ormar/queryset/queries/prefetch_query.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import abc
import copy
import logging
from abc import abstractmethod
from typing import TYPE_CHECKING, Any, Sequence, Union, cast
Expand Down Expand Up @@ -300,6 +301,7 @@ def _extract_own_order_bys(self) -> list["OrderAction"]:
order_by.target_model == self.relation_field.to
and order_by.related_str.endswith(f"{own_path}")
):
order_by = copy.copy(order_by)
order_by.is_source_model_order = True
order_by.table_prefix = self.table_prefix
own_order_bys.append(order_by)
Expand Down
17 changes: 17 additions & 0 deletions tests/test_relations/test_prefetch_related.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,3 +356,20 @@ async def test_prefetch_related_with_select_related_and_fields():
assert album.shops[0].name is None
assert album.shops[0].division is not None
assert album.shops[0].division.name is None


@pytest.mark.asyncio
async def test_prefetch_related_with_order_by_reusable_queryset():
async with base_ormar_config.database:
async with base_ormar_config.database.transaction(force_rollback=True):
album = await Album.objects.create(name="Malibu")
await Cover.objects.create(title="Cover1", album=album, artist="Artist 1")
await Cover.objects.create(title="Cover2", album=album, artist="Artist 2")

queryset = Album.objects.prefetch_related("cover_pictures").order_by(
"-cover_pictures__artist"
)
for _ in range(2):
albums = await queryset.all()
assert len(albums) == 1
assert albums[0].cover_pictures[0].artist == "Artist 2"
Loading