首页 > 解决方案 > 尽管存在对象,但“NoneType”对象没有属性“seventh_five”

问题描述

我正在创建一个用户可以创建项目的网站。每个项目有 10 个宏观问题。每个宏观问题都有子问题。

我正在尝试检索宏观问题的答案。

projects_id包含我数据库中的所有项目。

  projects = Project.objects.all()
  projects_id = []
  for project in projects:
    projects_id.append(project.id)

所以我做了一个for循环:

  for project_id in projects_id:
    seventh_question_project = Seventhquestion.objects.all().filter(project=project_id).first()
    answer_seventh_five = seventh_question_project.seventh_five
        if answer_seventh_five == "No":
           unaudited_projects.append(answer_seventh_five)
        else:
           audited_projects.append(answer_seventh_five)

如果我使用控制台,我可以检索answer_seventh_five

在此处输入图像描述

但是,如果加载页面,我会得到:

“NoneType”对象没有属性“seventh_five”

由于存在,我无法解释answer_seventh_five(因为我通过控制台检索它来测试它)

可能原因是我正在过滤而不是使用get.

我试过了:

seventh_question_project = Seventhquestion.objects.get(project=project_id)

但我得到:

第七题匹配查询不存在。

但是: seventh_question_project = Seventhquestion.objects.all()有效

标签: pythondjango

解决方案


不要通过ID。这不是 Django ORM 的用途。只需循环浏览项目本身:

for project in Project.objects.all():
    seventh_question_project = Seventhquestion.objects.all().filter(project=project).first()  # <-- not project_id!
    # or better:
    # seventh_question_project = project.seventhquestion_set.first()  
    if seventh_question_project:
        # you should always check, because you need to write fool-proof code
        answer_seventh_five = seventh_question_project.seventh_five
        ...

但是通过关系,您可以更轻松地获取相关对象。因此,假设模型上的project字段是 a ,则相反的关系是:OneToOneFieldSeventhquestionseventhquestion

for project in Project.objects.all():
    if hasattr(project, "seventhquestion"):
        # still need to check, you never know
        answer_seventh_five = project.seventhquestion.seventh_five
        ...

推荐阅读