Django queryset如果语句永远不会计算为true?

时间:2018-05-18 18:58:04

标签: python django django-queryset

我有一个简单的更新视图。它从先前的视图中读取POST请求。这部分效果很好。

owner = ADMirror.objects.get (employeentname=request.POST.get('userpost'))

我的查询集定义为:

currentlevel = QVReportAccess.objects.filter(ntname = 'owner.employeentname, active = 1).values('sr_datareduce_summary_code')

印刷品看起来像:

<QuerySet [{'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_c
ode': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_sum
mary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_dataredu
ce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_da
tareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {
'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z0712
6'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code': 'Z07126'}, {'sr_datareduce_summary_code':
'Z07126'}, '...(remaining elements truncated)...']>

查询集将具有sr_datareduce_summary_code的重复项,因为它们位于模型中的各个程序级别。

然后我有以下if语句给出yes如果为true而no为if,但即使查询集包含Z07126我的if语句永远不会计算为true。为什么这样,我怎样才能让它正常工作?

if QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1).values_list('sr_datareduce_summary_code') == "Z07126":
    appaccess = 'yes'
else:
    appaccess = 'no'

print(appaccess)

3 个答案:

答案 0 :(得分:2)

您正在将列表与字符串进行比较,这将永远不会成为现实

您只需要检查过滤器中的代码exists

if QVReportAccess.objects.filter(ntname = owner.employeentname, active = 1, sr_datareduce_summary_code= "Z07126").exists():

或者如果您需要保留values_list,请将其分配给变量,并将invalues_list('sr_datareduce_summary_code', flat=True)

一起使用
if 'Z07126' in my_query_list:

答案 1 :(得分:1)

或者您可以循环过滤的Queryset:

for obj in QVReportAccess.objects.filter(
    ntname=owner.employeentname, 
    active=1, 
    sr_datareduce_summary_code="Z07126"):

    # do something with obj
    print(obj.sr_datareduce_summary_code)

答案 2 :(得分:1)

queryset = QVReportAccess.objects.filter(ntname=owner.employeentname, active=1).values_list('sr_datareduce_summary_code', flat=True)

if queryset.exists() and str(queryset[0]) == "Z07126":
    appaccess = 'yes'
else:
    appaccess = 'no'

print(appaccess)

所以filter()基本上返回queryset而不是对象,它也可能是空白的,检查查询集是否为空的最佳方法是使用exists() 迭代时values_list()返回元组。每个元组都包含传递给它的相应字段的值。

如果只传入一个字段,也可以传入flat参数。如果为True,则表示返回的结果是单个值,而不是一个元组。您未通过flat=True时的示例:

>>> Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]

当您通过flat=True时:

>>> Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]

我希望你能解决问题。