python - 尽管存在对象,但“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()
有效
解决方案
不要通过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 ,则相反的关系是:OneToOneField
Seventhquestion
seventhquestion
for project in Project.objects.all():
if hasattr(project, "seventhquestion"):
# still need to check, you never know
answer_seventh_five = project.seventhquestion.seventh_five
...
推荐阅读
- c# - “智能”汽车在相同的输入下表现不同
- reactjs - 如何将父项目中的 npm 包导入到我的库中
- jestjs - 重复的文件名 - index.js - jest-haste-map
- html - 如何将 Ransack 参数 [:q] 从索引传递到同一控制器的更新操作以维护过滤结果?
- javascript - 如何防止css水平选框动画重置
- javascript - 如何在javascript中设置th标签的宽度等于它下面的td标签的宽度?
- javascript - 如何获得最终的重定向网址?
- javascript - 在javascript中将INT64字符串转换为INT64数字
- css - CSS 无法与 ReactJS 一起正常工作
- ios - 如何在快速启动屏幕后展示自己的视图控制器?