尽管存在对象,但“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:

http://img4.mukewang.com/6268d4920001c3e402920076.jpg

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

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

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

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

我试过:

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

但我得到:

第七题匹配查询不存在。

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


开满天机
浏览 103回答 2
2回答

慕虎7371278

不要通过ID。这不是 Django ORM 的用途。只需循环浏览项目本身:for project in Project.objects.all():&nbsp; &nbsp; seventh_question_project = Seventhquestion.objects.all().filter(project=project).first()&nbsp; # <-- not project_id!&nbsp; &nbsp; # or better:&nbsp; &nbsp; # seventh_question_project = project.seventhquestion_set.first()&nbsp;&nbsp;&nbsp; &nbsp; if seventh_question_project:&nbsp; &nbsp; &nbsp; &nbsp; # you should always check, because you need to write fool-proof code&nbsp; &nbsp; &nbsp; &nbsp; answer_seventh_five = seventh_question_project.seventh_five&nbsp; &nbsp; &nbsp; &nbsp; ...但是通过关系,您可以更轻松地获取相关对象。因此,假设模型上的project字段是 a ,则相反的关系是:OneToOneFieldSeventhquestionseventhquestionfor project in Project.objects.all():&nbsp; &nbsp; if hasattr(project, "seventhquestion"):&nbsp; &nbsp; &nbsp; &nbsp; # still need to check, you never know&nbsp; &nbsp; &nbsp; &nbsp; answer_seventh_five = project.seventhquestion.seventh_five&nbsp; &nbsp; &nbsp; &nbsp; ...

缥缈止盈

这个怎么样?seventh_question_project = Seventhquestion.objects.filter(project=project_id).first()answer_seventh_five = seventh_question_project.seventh_five
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python