开发者

Return a model from a custom query without hitting the database

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 pres开发者_运维问答ume that this will hit the database, on function return

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


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜