亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

盡管存在對象,但“NoneType”對象沒有屬性“seventh_five”

盡管存在對象,但“NoneType”對象沒有屬性“seventh_five”

開滿天機 2022-04-27 13:28:30
我正在創建一個用戶可以創建項目的網站。每個項目有 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()有效
查看完整描述

2 回答

?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

不要通過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

        ...


查看完整回答
反對 回復 2022-04-27
?
縹緲止盈

TA貢獻2041條經驗 獲得超4個贊

這個怎么樣?


seventh_question_project = Seventhquestion.objects.filter(project=project_id).first()

answer_seventh_five = seventh_question_project.seventh_five


查看完整回答
反對 回復 2022-04-27
  • 2 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號