[英]Django queryset If statement never evaluates to 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語句,如果為true,則為yes,如果為false,則為no,但是即使查詢集包含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
,將其分配給一個變量,並使用in
與values_list('sr_datareduce_summary_code', flat=True)
if 'Z07126' in my_query_list:
或者,您可以循環過濾的查詢集:
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)
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, ...]
希望您能解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.