【问题标题】:django: forms foreign key auto corellationdjango:形成外键自动关联
【发布时间】:2014-10-21 13:35:13
【问题描述】:

我必须建模(人口统计 + 诊断),我已经为这些创建了 2 个相应的表格。

models.py

class demographic(models.Model):
    national_health_care_pat_id = models.IntegerField('National Health Care patient id', null=True,blank=True)
    patient_hospital_file_number = models.IntegerField(null=True,blank=True)
    patient_id = models.IntegerField(unique= True ,primary_key=True)

    def __str__(self):
        return str(self.patient_id)

class diagnosis(models.Model):
    patient = models.ForeignKey(demographic)
    age_of_diagnosis = models.IntegerField(null=True,blank=True)

    def __str__(self):
        return str(self.patient_id)

views.py

def input(request):

form = DemographicForm(request.POST or None)
form_diag = DiagnosisForm(request.POST or None)


context = RequestContext(request)

if form.is_valid():
    save_it = form.save(commit=False)
    save_it.save()
    return render_to_response('test.html')

if form_diag.is_valid():
    save_itd = form_diag.save(commit=False)
    save_itd.save()
    return render_to_response('test.html')

return render_to_response('input.html', {'frm':form, 'frm_d': form_diag}, context)

在我的模板 input.html 我有

<form class="tab-pane fade in active" id="demographics" method="post" >
    {%crispy frm%}
</form>
<form class="tab-pane fade" id="diagnosis" method="post">
    {%crispy frm_d%}
</form>

forms.py

class DemographicForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(DemographicForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        self.fields['date_of_birth'].widget = widgets.AdminDateWidget()
        self.helper.layout = Layout(
            'national_health_care_pat_id',
            'patient_hospital_file_number',
            'patient_id',

            FormActions(
                Submit('submit', "Save changes"),
                Submit('cancel', "Cancel")
            ),

        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = demographic
        exclude = []

class DiagnosisForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(DiagnosisForm, self).__init__(*args, **kwargs)
        self.helper=FormHelper(self)
        self.helper.layout = Layout(
            'patient',
            'age_of_diagnosis',

            FormActions(
                Submit('submit', "Save changes"),
               Submit('cancel',"Cancel")
            ),
        )
        self.helper.form_tag = False
        self.helper.form_show_labels = True

    class Meta:
        model = diagnosis
        exclude = []

有没有办法将表格上的人口统计.患者_id 与诊断.患者相关联?我的意思是我填写并保存人口统计表格,然后我填写诊断表格我希望我的表格在诊断.患者中具有人口统计.患者 ID 值而不选择它。

【问题讨论】:

  • 看到那段代码我就头疼。这与您要问的内容无关,但是将事情分开不是更有意义吗?只是为了可读性(以及可维护性和扩展行为)。您已经有几个名为 foo_fieldname 的字段,那么为什么不使用这些字段创建一个 Foo 类并将它们链接起来,而不是拥有一个包含一百万个字段的巨大模型呢?
  • @yuvi 是的,我真的很抱歉!我做的。关于你的最后一个问题,那不是我的职责。我必须为这个问题提供一个解决方案。
  • 嗯,对于初学者,您可能希望将两个表单合并为一个,然后按逻辑保存patient,并在保存第二个时使用新创建的对象。
  • 等一下 - tab-pane?您是否正在寻找一种方法来实现逐步类型的表单,通常称为Form Wizard?另见我的answer here
  • @yuvi 不,我不想实现 formWizard。 tab-pane 用于引导模板

标签: python django forms django-models django-forms


【解决方案1】:

如果你想要一个初始值,你可以试试this

form = MyForm(initial={'max_number': '3'})

您需要将 3 替换为您的患者 ID,您需要弄清楚如何将其传递给视图。如果您尝试类似以下内容,这很容易:

my_demographic_object = my_demographic_form.save() #Object created from your old form
form = MyForm(initial={'patient': my_demographic_object.id})

如果这不是你想要做的,请详细解释一下

【讨论】:

  • 谢谢。当我使用form = MyForm(initial={'patient': my_demographic.id}) 时,我得到'DemographicForm' object has no attribute 'id'
  • 您使用的是表单对象,而不是人口统计对象。为清晰起见进行编辑。
  • my_demographics = DemographicForm(request.POST or None)my_demographics.save() 之后的下一个我有mydiagnosis= DiagnosisForm(initial={'patient': my_demographics.patient_id})。这样不行吗?
  • 我编辑了我的答案。我从 my_demographics.save() 行获得了对人口统计对象的引用
  • 就是这样!非常感谢!
猜你喜欢
  • 2015-08-16
  • 1970-01-01
  • 1970-01-01
  • 2021-04-21
  • 1970-01-01
  • 1970-01-01
  • 2011-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多