Hi cool-RR,
The following should do:
filtered_chairs = Chair.objects.filter(some_other_lookup=whatever)
desks = Desk.objects.prefetch_related(
PrefetchRelated('chairs', filtered_chairs, to_attr='filered_chairs'),
PrefetchRelated('nearby_chairs', filtered_chairs,
to_attr='filtered_nearby_chairs'),
)
from itertools import chain
for desk in desks:
for chair in chain(desk.filtered_chairs, desk.filtered_nearby_chairs):
# ....
It will issue only three queries independently of the number of Chair or
Desks you have.
Simon
Le mercredi 25 février 2015 15:05:50 UTC-5, cool-RR a écrit :
>
> Hi guys,
>
> I'm trying to solve a problem using the new `Prefetch` but I can't figure
> out how to use it.
>
> I have these models:
>
> class Desk(django.db.models.Model):
> pass
>
> class Chair(django.db.models.Model):
> desk = django.db.models.Foreignkey('Desk', related_name='chair',)
> nearby_desks = django.db.models.ManyToManyField(
> 'Desk',
> blank=True,
> )
>
> I want to get a queryset for `Desk`, but it should also include a
> prefetched attribute `favorite_or_nearby_chairs`, whose value should be
> equal to:
>
> Chair.objects.filter(
> (django.db.models.Q(nearby_desks=desk) |
> django.db.models.Q(desk=desk)),
> some_other_lookup=whatever,
> )
>
> Is this possible with `Prefetch`? I couldn't figure out how to use the
> arguments.
>
>
> Thanks,
> Ram.
>
--
You received this message because you are subscribed to the Google Groups
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-users/726492e7-5f82-4690-a97c-20743592c3f8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.