Wednesday, March 2, 2011

Query Builder & temporary tables

Hi,

using the PostgreSQL backend I have a complex query
q = Model.objects.filter(…)
that selects some objects using multiple joins and some geoDjango magic.

Then there are some other simpler queries like
q2 = OtherModel.filter(foreign__in = q.query)
q3 = YetAnotherModel.filter(foreign__in = q.query)

I don't actually evaluate q but it's only input for the others. Now
evaluating q2 and q3 of course leads to basically executing q two times,
as a subquery.

So I would like to do a `CREATE TEMPORARY TABLE temp_q AS <query from
q>` and use this table for q2 and q3, something like:

new_q = Model.objects.raw('SELECT * FROM temp_q')
q2 = OtherModel.filter(foreign__in = new_q.query)
q3 = YetAnotherModel.filter(foreign__in = new_q.query)

My question: what is the nice way to do this? I would fall back to
string manipulation 'CREATE…AS ' + str(q.query) and using a cursor to
run this, but this feels hacky.

Of course q might still return a lot of objects, so creating a list of
primary keys in python and passing that as a parameter is no good either.

Cheers,
--
Pascal Germroth

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment