Skip to content

Commit

Permalink
Better specify nested prefetch lookups
Browse files Browse the repository at this point in the history
  • Loading branch information
fjsj committed Jan 19, 2024
1 parent 0a7196e commit c53bf3e
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.2.0]

- Add support to nested prefetch lookups like `v.VirtualModel(manager=User.objects, lookup="course__facilitators")`
* Warning: this will remain undocumented for now, because the behavior is strange:
the prefetch is made inside `course` in this case, due to Django behavior.
- Add parameter `serializer_context` to be used in `v.Annotation` and `get_prefetch_queryset`.

## [0.1.6]

- Fix support for custom manager in `VirtualModel` initialization
Expand Down
4 changes: 2 additions & 2 deletions tests/optimization/test_lookup_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,8 @@ class Meta:

@hints.defined_on_virtual_model()
def get_facilitator_users(self, lesson):
if hasattr(lesson, "facilitator_users"):
return list({u.email for u in lesson.facilitator_users})
if hasattr(lesson.course, "facilitator_users"):
return list({u.email for u in lesson.course.facilitator_users})

# this won't run because it's defined on virtual model,
# but one could add fallback code here:
Expand Down
20 changes: 20 additions & 0 deletions tests/virtual_models/test_virtual_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,3 +432,23 @@ class Meta:

for completed_lesson in completed_lesson_list:
assert isinstance(completed_lesson.lesson.course.created_by, User)

def test_prefetch_with_nested_lookup(self):
class VirtualLesson(v.VirtualModel):
facilitator_users = v.VirtualModel(manager=User.objects, lookup="course__facilitators")

class Meta:
model = Lesson

virtual_model = VirtualLesson()
qs = Lesson.objects.all()
lookup_list = ["facilitator_users"]

optimized_qs = virtual_model.get_optimized_queryset(qs=qs, lookup_list=lookup_list)
with self.assertNumQueries(3):
lesson_list = list(optimized_qs)
assert len(lesson_list) == 9

for lesson in lesson_list:
for user in lesson.course.facilitator_users:
assert isinstance(user, User)

0 comments on commit c53bf3e

Please sign in to comment.