Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM and hitting DB

Tags:

orm

django

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?

like image 934
alexvassel Avatar asked May 13 '11 08:05

alexvassel


People also ask

Does Django filter hit database?

Django Queryset is generally lazy in nature. It will not hit the database until it evaluates the query results.

Is Django ORM a database?

One of the most powerful features of Django is its Object-Relational Mapper (ORM), which enables you to interact with your database, like you would with SQL. In fact, Django's ORM is just a pythonical way to create SQL to query and manipulate your database and get results in a pythonic fashion.

What is the difference between Select_related and Prefetch_related?

select_related() “follows” foreign-key relationships, selecting additional related-object data when it executes its query. prefetch_related() does a separate lookup for each relationship and does the “joining” in Python.

Why are Querysets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.


1 Answers

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']
like image 50
dting Avatar answered Oct 24 '22 15:10

dting