简体   繁体   中英

Django Select Query to get multiple columns with condition

I've a table/model 'ABC' that has two column fields 'A' and 'B'. I want to query the above table as follows:

select A, B from ABC where B is not null;

I'm able to do

select A, B from ABC;

but I don't know how to introduce the null check condition. I've tried the following with no success:

ABC.objects.values('A', 'B')  # which is getting all the tuples including null valued 'B' column
ABC.objects.values('A', 'B', 'B__isnull=False')  # which is incorrect
ABC.objects.values('A', 'B__isnull=False')  # which is incorrect again.

Can someone provide the correct format/query which I can use?

Thanks.

Try using the filter method:

ABC.objects.filter(B__isnull=False).values('A', 'B')

As you mention it is also possible to use exclude :

ABC.objects.exclude(B__isnull=True).values('A', 'B')

The exclude method is the same as a filter, it just puts a not around the condition that is matched. They're the perfect opposites, it's just the code will read better with filter in some circumstances, and exclude with other conditions.

There is one minor note in the docs about when the ordering of calls like exclude and values , but it doesn't make a logical difference:

Finally, note that a ValuesQuerySet is a subclass of QuerySet and it implements most of the same methods. You can call filter() on it, order_by(), etc. That means that these two calls are identical:

Blog.objects.values().order_by('id')
Blog.objects.order_by('id').values()

The people who made Django prefer to put all the SQL-affecting methods first, followed (optionally) by any output-affecting methods (such as values()), but it doesn't really matter. This is your chance to really flaunt your individualism.

没关系,我明白了:)

ABC.objects.values('A', 'B').exclude(B__isnull=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM