开发者

Return a model from a custom query without hitting the database

开发者 https://www.devze.com 2023-01-14 19:27 出处:网络
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 ex

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

精彩评论

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