views:

22

answers:

1

Hi,

I have a custom query which eventually returns a list of objects. I need the function to return the actual objects but I don't want to hit the database twice for every query since it's already an expensive query. How can i return a model instance without hitting the db?

NB: I presume doing something like the following will actually create a new instance of a different model?

return [Object(pk=row[0]) for row in results]

NB: I also presume that this will hit the database, on function return

return [Object.objects.get(pk=row[0]) for row in results]
+1  A: 

If you have Django 1.2+ you can use the raw() method to return list of Model instances using the results of a custom query. Something like this in your case:

query = "<your query goes here>"
Object.objects.raw(query)
Manoj Govindan
Oh awesome. I've just switched to 1.2 and must have missed that in the release notes!
Duncan