alexvassel
alexvassel

Reputation: 10740

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?

Upvotes: 13

Views: 8730

Answers (3)

dting
dting

Reputation: 39287

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']

Upvotes: 19

DrTyrsa
DrTyrsa

Reputation: 31951

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.

Upvotes: 3

Zach Kelling
Zach Kelling

Reputation: 53829

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.

Upvotes: 1

Related Questions