在我的应用程序中,我有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
之间的连接。这是不是在视图中执行得更好
目前没有回答
相关问题 更多 >
编程相关推荐