Opened 10 years ago

Closed 10 years ago

Last modified 10 years ago

#24414 closed Cleanup/optimization (fixed)

Add example of Prefetch object usage to docs

Reported by: Ram Rachum Owned by: sww
Component: Documentation Version: dev
Severity: Normal Keywords:
Cc: cmawebsite@… Triage Stage: Ready for checkin
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Change History (8)

comment:1 by Collin Anderson, 10 years ago

Cc: cmawebsite@… added
Triage Stage: UnreviewedAccepted

agreed

comment:2 by Collin Anderson, 10 years ago

Here's a snippet from my code:

posts = Post.objects.filter(post_type='post', post_status='publish').exclude(id=self.id).order_by('-post_date')
self.categories.prefetch_related(Prefetch('post_set', queryset=posts, to_attr='posts'))
Version 0, edited 10 years ago by Collin Anderson (next)

comment:3 by sww, 10 years ago

Here's my stab at an example:

>>> Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

>>> voted_choices = Choice.objects.filter(votes__gt=0)
>>> voted_choices
[<Choice: The sky>]

>>> Question.objects.prefetch_related(Prefetch('choice_set', queryset=voted_choices)).get().choice_set.all()
[<Choice: The sky>]

# Providing the to_attr value will preserve the choice_set results.
>>> Question.objects.prefetch_related(Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')).get().voted_choices
[<Choice: The sky>]
>>> Question.objects.prefetch_related(Prefetch('choice_set', queryset=voted_choices, to_attr='voted_choices')).get().choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

Feedback?

comment:4 by Collin Anderson, 10 years ago

Has patch: set

Seems fine to me, though shorter would be better in my opinion. Want to make a pull request?

comment:5 by sww, 10 years ago

Owner: changed from nobody to sww
Status: newassigned

comment:6 by Simon Charette, 10 years ago

Triage Stage: AcceptedReady for checkin
Type: New featureCleanup/optimization
Version: 1.7master

The pull request LGTM but a final review from a native speaker can't hurt :)

comment:7 by Simon Charette <charette.s@…>, 10 years ago

Resolution: fixed
Status: assignedclosed

In a3e89f13:

Fixed #24414 -- Added examples of Prefetch object usage to the docs.

comment:8 by Simon Charette <charette.s@…>, 10 years ago

In e0e2df41:

[1.8.x] Fixed #24414 -- Added examples of Prefetch object usage to the docs.

Backport of a3e89f13dfb1f22a26ead8b06b37695598a4421a from master

Note: See TracTickets for help on using tickets.
Back to Top