2 回答

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
...

TA貢獻2041條經驗 獲得超4個贊
這個怎么樣?
seventh_question_project = Seventhquestion.objects.filter(project=project_id).first()
answer_seventh_five = seventh_question_project.seventh_five
添加回答
舉報