首页 > 解决方案 > 为什么related_name 不适用于模型?

问题描述

有相互关联的问答表。每个问题都有一个答案。我需要检查 CompanyGeneralInfoAnswers 模型中的答案字段。

class CompanyGeneralInfoQuestion(models.Model):
    rfi = models.ForeignKey(Rfis, models.DO_NOTHING)
    question = models.CharField(max_length=512)

    class Meta:
        db_table = 'company_info__questions'


class CompanyGeneralInfoAnswers(models.Model):
    question = models.OneToOneField('CompanyGeneralInfoQuestion', models.DO_NOTHING, related_name='answer_to_question')
    answer = models.CharField(max_length=4096, blank=True, null=True)
    class Meta:
        db_table = 'company_info_answers'

为此,我提出了这个要求。

round = kwargs.get('rfiid')
exist_company_question = CompanyGeneralInfoQuestion.objects.filter(rfi=round)
if exist_company_question:
    for q in exist_company_question:
        print(q.answer_to_question.answer)

但是遇到了错误

RelatedObjectDoesNotExist: CompanyGeneralInfoQuestion has no answer_to_question.

标签: django

解决方案


推荐阅读