Search code examples
djangodjango-modelsdjango-database

django filter and exclude effect on performance?


I read filter and exclude from django documentation but I want to know that if I will use following code:

Entry.objects.filter(
   ...     headline__startswith='What'
  ... ).exclude(
 ...     pub_date__gte=datetime.now()
 ... ).filter(
 ...     pub_date__gte=datetime(2005, 1, 1)
 ... )

then , will it be resulted in 1 query or 4 queries? Will it first query and get all the objects and then will filter and exclude after fetching all records from mysql/db or it will all be done on mysql/db level. Because if it will not be done on db level then it can result in performance problem. thats why I want to know that will filter and exclude work on app level or db level?


Solution

  • I got the answer of my question, that is: The query will be executed only once as said in own django documentation:

    QuerySets are lazy -- the act of creating a QuerySet doesn't involve any database activity. You can stack filters together all day long, and Django won't actually run the query until the QuerySet is evaluated and Though this looks like three database hits, in fact it hits the database only once, at the last line (print q). In general, the results of a QuerySet aren't fetched from the database until you "ask" for them. When you do, the QuerySet is evaluated by accessing the database. For more details on exactly when evaluation takes place, see "When QuerySets are evaluated".