[英]Django Select Query to get multiple columns with condition
I've a table/model 'ABC' that has two column fields 'A' and 'B'. 我有一个具有两个列字段“ A”和“ B”的表/模型“ ABC”。 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: 尝试使用
filter
方法:
ABC.objects.filter(B__isnull=False).values('A', 'B')
As you mention it is also possible to use exclude
: 如您所述,也可以使用
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. exclude方法与过滤器相同,只是将一个
not
在匹配条件周围。 They're the perfect opposites, it's just the code will read better with filter in some circumstances, and exclude with other conditions. 它们是完全相反的,只是在某些情况下使用filter可以使代码更好地读取,而在其他情况下则可以使代码更好地读取。
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: 在文档中,有一个小小的注释 , 说明何时调用诸如
exclude
和values
的顺序,但这并没有逻辑上的区别:
Finally, note that a ValuesQuerySet is a subclass of QuerySet and it implements most of the same methods.
最后,请注意,ValuesQuerySet是QuerySet的子类,它实现了大多数相同的方法。 You can call filter() on it, order_by(), etc. That means that these two calls are identical:
您可以在其上调用filter(),order_by()等。这意味着这两个调用是相同的:
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.
创建Django的人更喜欢将所有影响SQL的方法放在首位,然后(可选)再加上任何影响输出的方法(例如values()),但这并不重要。 This is your chance to really flaunt your individualism.
这是您真正炫耀个人主义的机会。
没关系,我明白了:)
ABC.objects.values('A', 'B').exclude(B__isnull=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.