Python如果使用queryset在视图中声明

时间:2017-12-04 18:18:00

标签: django

我尝试使用以下if语句,如果reportaccess等于使用以下内容的所有报告,则该语句将显示空集。

if reportaccess == 'All Reports':
    bhreportgrouplist = None
    cereportgrouplist = None
    finreportgrouplist = None
    careportgrouplist = None
    pireportgrouplist = None
    screportgrouplist = None
    dssreportgrouplist = None
    psgreportgrouplist = None
    othreportgrouplist = None

else:
    bhreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 200)
    cereportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 500)
    finreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 600)
    careportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 800)
    pireportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1100)
    screportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1200)
    dssreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1300)
    psgreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 1400)
    othreportgrouplist = QvReportList.objects.filter(~Q(report_id__in= reportIds)).filter(report_group_id = 99999)

当视图通过时,它始终显示Else,但当我查看reportaccess的打印时,它显示为:

 <QuerySet ['All Reports']>  

为什么我的条件没有得到满足?我怎样才能实现

1 个答案:

答案 0 :(得分:1)

if reportaccess == 'All Reports'的检查不会返回True,因为在您的打印中,reportaccess是一个Queryset,您将它与一个永远不会相等的字符串进行比较。< / p>

您可以通过运行

来验证这一点
from django.db.models.query import QuerySet
isinstance(reportaccess, QuerySet)

看起来你想要的是检查你的Queryset reportaccess是否包含'所有报告',所以像这样:

something = 'All Reports'
if something in reportaccess:
    #do stuff