在我的应用中,我以Study
作为中心模型。 Study
个具有多个Strata
,每个Strata
具有多个Level
。用户通过为与该研究相关联的每个Allocation
选择一个级别来为研究创建Strata
,例如:
class Study(models.Model):
name = models.CharField(max_length=100)
class Stratum(models.Model):
study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='strata')
name = models.CharField(max_length=100)
class Level(models.Model):
stratum = models.ForeignKey(Stratum, on_delete=models.CASCADE, related_name='levels')
label = models.CharField(max_length=100)
class Allocation(models.Model):
study = models.ForeignKey(Study, on_delete=models.CASCADE, related_name='allocations')
code = models.CharField(blank=False, max_length=100)
levels = models.ManyToManyField(Level, related_name='allocations')
为了为分配创建表单创建字段,我目前在表单的构造函数中找到所有Strata
和关联的级别,但是由于用户不与之交互而隐藏了层次:
class AllocationForm(forms.ModelForm):
class Meta:
model = Allocation
fields = ('code',)
def __init__(self, *args, **kwargs):
study = kwargs.pop('study')
super(AllocationForm, self).__init__(*args, **kwargs)
strata = Stratum.objects.filter(study=study)
for stratum in strata:
self.fields[stratum.name] = forms.IntegerField(
widget=forms.HiddenInput()
)
self.fields[stratum.name].initial = stratum.id
self.fields[stratum.name].disabled = True
self.fields[stratum.name + '_level'] = forms.ModelChoiceField(
queryset=Level.objects.filter(stratum=stratum)
)
这是将关联对象附加到表单的安全且明智的方法吗?我担心在尝试创建分配时将无法跟踪Strata
和Level
之间的连接。在视图中这样做会更好吗?