开发者

Django ORM and hitting DB

When I do something like

I. objects = Model.objects.all()

and then

II. objects.filter(field_1=some_condition)

I hit db every 开发者_如何转开发time when on the step 2 with various conditions. Is there any way to get all data in first action and then just take care of the result?


You actually don't hit the db until you evaluate the qs, queries are lazy.

Read more here.

edit:

After re-reading your question it becomes apparent you were asking how to prevent db hits when filtering for different conditions.

qs = SomeModel.objects.all()

qs1 = qs.filter(some_field='some_value')
qs2 = qs.filter(some_field='some_other_value')

Usually you would want the database to do the filtering for you.

You could force an evaluation of the qs by converting it to a list. This would prevent further db hits, however it would likely be worse than having your db return you results.

qs_l = list(qs)
qs1_l = [element for element in qs_l if element.some_field='some_value']
qs2_l = [element for element in qs_l if element.some_field='some_other_value']


Of course you will hit db every time. filter() transforms to SQL statement which is executed by your db, you can't filter without hitting it. So you can retrieve all the objects you need with values() or list(Model.objects.all()) and, as zeekay suggested, use Python expressions (like list comprehensions) for additional filtering.


Why don't you just do objs = Model.objects.filter(field=condition)? That said, once the SQL query is executed you can use Python expressions to do further filtering/processing without incurring additional database hits.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜