python - 检查 None 类型上是否存在查询集的逻辑?

标签 python

当代码中有超过 20 个组时,我在下面展示了包含 2 个组的示例。不知道是否有更好的方法,如果有请提出建议。

下面我将检查学生的学生组是否有“所有组”,如果有,我希望将组设置为“无”。这部分工作正常,与其他部分相同。

    allgroups = 'All Groups'
# if user has all groups then no group will show
    if allgroups in studentgroup:
        bhstudentgrouplist = None
        abstudentgrouplist = None
    else:
        bhstudentgrouplist = Groups.objects.filter(~Q(group_id__in= 
        groupIds)).filter(group_id = 2000)
        abstudentgrouplist = Groups.objects.filter(~Q(group_id__in= 
        groupIds)).filter(group_id = 5000)

发生的情况是,如果用户拥有组中可能的所有项目,则应将它们标记为“无”,这样它们就不会显示在我的模板中。为了做到这一点,我尝试了以下方法:

1.

if not bhstudentgrouplist.exists():
    bhstudentgrouplist = None
if not abstudentgrouplist.exists():
    abstudentgrouplist = None

2.

if bhstudentgrouplist.count() < 1:
    bhstudentgrouplist = None
if not abstudentgrouplist.count() < 1:
    abstudentgrouplist = None

3.

if bhstudentgrouplist.isnull():
    bhstudentgrouplist = None
if not abstudentgrouplist.isnull():
    abstudentgrouplist = None

这适用于实例,但当学生拥有所有组时,我收到错误无法在 None 类型上使用函数 isnull()、count()、exists() 。当该组属于“所有组”并且学生已经拥有学生组中的所有报告,因此需要将其设置为“无”时,我该如何解决?如果有更好的方法来完成整个过程,请指导我朝这个方向前进。

该过程正在检查学生是否拥有“所有小组”,如果没有,它将提供可用报告的列表。有时,在这些情况下,用户已经拥有所有可用报告,因此报告组应设置为“无”,因此不会返回可用报告。

最佳答案

您不应将 bhstudentgrouplist 设置为 None,而应将其设置为空查询集。那么它仍然可以访问查询集函数

 if allgroups in studentgroup:
    bhstudentgrouplist = Groups.objects.none()
    abstudentgrouplist = Groups.objects.none()
else:
    b...

然后查询集成员函数,例如bhstudentgrouplist.count() = 0 工作,虽然我不确定 isnull()

关于python - 检查 None 类型上是否存在查询集的逻辑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262427/

相关文章:

python - #X 格式说明符真的应该使 "0x"前缀大写吗?

python - 颜色条打断轴

python - Django 测试需要很长时间才能启动

python - 如何对月份和年份列重新索引以插入丢失的数据?

python - 将整个 Pandas 数据框转换为 Pandas (0.17.0)中的整数

python - 开机后自动运行 python 脚本?

python - 更改 HTML 标记内的属性以查看完整内容 Python BeautifulSoup

Python mechanize 不点击按钮

python - 如何有效地链接 ipyparallel 任务并将中间结果传递给引擎?

python - Anaconda Python安装错误