Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to exclude multiple values of column using Django ORM?

I want to filter mytable & get rows where name does not contain '' or '-' values and for this purpose I have used below query but does not working.

mytable.objects.exclude(name = ['','-']).order_by('name').count() returning 2000 all rows and whereas query mytable.objects.exclude(name = '').order_by('name').count() working perfectly and returning filtered 1460 results.

Below one is my Postgresql query which is working perfectly fine and returning 1450 results excluding name values of ['','-'].

select * from mytable where name != '-' and name != '' order by -id

like image 493
Moon Avatar asked Nov 29 '19 07:11

Moon


People also ask

What is exclude in Django ORM?

The exclude() method from the QuerySet class returns all objects that do not match the given keyword arguments. So whatever data matches the parameter that is passed into the exclude() method will be excluded from the returned QuerySet.

Why Django ORM is 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.

What is __ in Django ORM?

Django Field Lookups Managers and QuerySet objects comes with a feature called lookups. A lookup is composed of a model field followed by two underscores ( __ ) which is then followed by lookup name.

Is Django ORM good?

The Django ORM is a very powerful tool, and one of the great attractions of Django. It makes writing simple queries trivial, and does a great job of abstracting away the database layer in your application. And sometimes, you shouldn't use it.


1 Answers

Try this.

mytable.objects.exclude(name__in=['', '-'])

This should exclude the rows matching the values you've passed in the list.

And you don't need to do order_by() for getting the count.

Just use the .count() directly on queryset.

like image 131
Underoos Avatar answered Oct 20 '22 22:10

Underoos