最简单的解释方法就是说出我要做的事情。
我有一个访问模型和一个主题模型。 访问是主题的外键,因此我可以将主题作为我的表单中的选择字段(这是一个基于访问模型构建的模型表单)。
我想要的其他数据虽然与主题有关,但我想知道最好的访问方式是什么。
我的模型,形式和我最终想要的是下面的。
楷模
class Subject(models.Model): def __unicode__(self): return self.subject_name subject_name=models.CharField(max_length=60,null=True, blank=True) subject_number=models.CharField(max_length=10,null=True, blank=True) birthdate=models.DateField("Date of Birth",null=True, blank=True) cohort=models.ForeignKey("Cohort",null=True, blank=True) class Visit(models.Model): def __unicode__(self): return self.id subject=models.ForeignKey("Subject") ageband=models.ForeignKey("AgeBand",null=True, blank=True) visit_date=models.DateField("Visit Date",null=True, blank=True)形成
class TestForm(ModelForm): class Meta: model = Visit widgets = { 'visit_date': DateInput(attrs={'class':'datepicker'}), }简单描述我想要的形式
主题名称_ (有这个)
主题编号_ _(有这个)
主题出生日_ _(来自Subject.birthdate,没有这个)
访问日期_ (有这个)
Simplest way to explain would be to just say what I'm trying to do.
I have a Visit model and a Subject model. The Visit is foreign-keyed to the Subject, so I can get the Subjects as a choice field in my form (which is a Model Form built off of the Visit model).
There is other data I want though that is related to the subject, and I was wondering what the best way to access that is.
My models, form and what I ultimately want are below.
Models
class Subject(models.Model): def __unicode__(self): return self.subject_name subject_name=models.CharField(max_length=60,null=True, blank=True) subject_number=models.CharField(max_length=10,null=True, blank=True) birthdate=models.DateField("Date of Birth",null=True, blank=True) cohort=models.ForeignKey("Cohort",null=True, blank=True) class Visit(models.Model): def __unicode__(self): return self.id subject=models.ForeignKey("Subject") ageband=models.ForeignKey("AgeBand",null=True, blank=True) visit_date=models.DateField("Visit Date",null=True, blank=True)Form
class TestForm(ModelForm): class Meta: model = Visit widgets = { 'visit_date': DateInput(attrs={'class':'datepicker'}), }Simple Depiction of what I want in form
Subject Name _ (have this)
Subject Number __ (have this)
Subject Birthdate __ (from Subject.birthdate, don't have this)
Visit Date _ (have this)
最满意答案
ModelForm仅表示来自一个模型的字段。 如果要使用这两个模型,则需要使用InlineFormSet ,它允许您组合两个ModelForm 。 从文档 :
内联表单集是模型表单集之上的一个小抽象层。 这些简化了通过外键处理相关对象的情况。
这是一个类似的答案 ,描述了如何创建InlineFormSet 。
ModelForm only represents fields from one model. If you want to use both models, you'll need to use an InlineFormSet, which allows you to combine two ModelForms. From the documentation:
Inline formsets is a small abstraction layer on top of model formsets. These simplify the case of working with related objects via a foreign key.
Here is a similar answer that describes how to create an InlineFormSet.
更多推荐
发布评论