Django 查询集 If 语句的计算结果永远不会为 true?



我有一个简单的更新视图。 这将从以前的视图中读取 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 语句,如果为真,则给出是,如果为假,则给出否,但即使查询集包含 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)

你正在将列表与字符串进行比较,这永远不会是真的

要么你只需要检查过滤器中是否存在该代码

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:
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而不是一个对象,它也可能是空白的,检查 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, ...]

我希望你能得到解决问题的想法。

或者你可以只循环过滤的查询集:

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)

最新更新