Re: Prefetch related data when using raw()

1,082 views
Skip to first unread message

akaariai

unread,
Jul 26, 2012, 3:44:45 PM7/26/12
to Django users
On 26 heinä, 19:12, Sencha <mich...@d3i.com> wrote:
> I want to prefetch related data (ideally through the prefetch_related()method), however I need to use the
> raw() mapper method that will map a custom query (complicated table joins
> to filter my query properly) to my model. However when I try this I get:
>
> AttributeError: 'RawQuerySet' object has no attribute 'prefetch_related'
>
> Is there any way I can achieve the prefetching when using
> Model.objects.raw()?
>
> Many thanks!

There is no direct way. However, you could try this (completely
untested, and not part of public api):

from django.db.models.query import prefetch_related_objects
raw_qs = list(raw_qs) # this line maybe not needed...
prefetch_related_objects(raw_qs, ['a_related_lookup',
'another_related_lookup', ...])

- Anssi

Sencha

unread,
Jul 30, 2012, 9:45:07 AM7/30/12
to django...@googlegroups.com
That's absolutely perfect, works like a charm! Thank you very much for the insight.
Reply all
Reply to author
Forward
Message has been deleted
0 new messages