Is there a drawback to using the .filter () filter. Filter (). Filter () ... "in Django?

Are the following two equivalent SQL query calls allowed in Django?

Connect multiple calls

Model.objects \ .filter(arg1=foo) \ .filter(arg2=bar) \ ... 

Combining all args together:

 Model.objects \ .filter(arg1=foo, arg2=bar) 

I would like the code to be readable (there are many filter calls than I showed), but only if there is no performance sacrifice.

+7
django django-models django-orm
Sep 17 '10 at 7:11
source share
2 answers

Update:

Do not pay attention to this answer. Better, the correct answer . Thanks @Sam for the heads.

Old answer:

Are the following two equivalent SQL query calls allowed in Django?

The short answer is yes. They will generate equivalent queries.

I checked this with the model I am using. created queries are functionally identical. The query contains different filter conditions AND ed.

I would like the code to be readable (there are many filter calls than I showed), but only if there is no performance sacrifice.

One way to achieve readability is to use a dictionary to collect all filter conditions. For example,

 conditions = dict(arg1 = foo, arg2 = bar, ....) conditions.update(argN = baz) Model.objects.filter(**conditions) 
+11
Sep 17 '10 at 7:17
source share

In addition to Manoj's answer, here you can parse the sql generated for the QuerySet :

 result1 = SomeModel.objects.filter(field1=100, field2=200) print "Result1", results1.query result2 = SomeModel.objects.filter(field1=100).filter(field2=200) print "Result2", result2.query 
+6
Sep 17 '10 at 7:28
source share



All Articles