[Solved]-Django ORM and hitting DB

18👍

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

2👍

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.

1👍

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.

Leave a comment