#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
Example needed here to clarify: https://docs.djangoproject.com/en/1.7/ref/models/queries/#django.db.models.Prefetch
Change History (8)
comment:1 by , 10 years ago
Cc: | added |
---|---|
Triage Stage: | Unreviewed → Accepted |
comment:2 by , 10 years ago
Here's a snippet from my code if it helps:
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'))
comment:3 by , 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 , 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 , 10 years ago
Owner: | changed from | to
---|---|
Status: | new → assigned |
comment:6 by , 10 years ago
Triage Stage: | Accepted → Ready for checkin |
---|---|
Type: | New feature → Cleanup/optimization |
Version: | 1.7 → master |
The pull request LGTM but a final review from a native speaker can't hurt :)
Note:
See TracTickets
for help on using tickets.
agreed