带有用户定义字段和外键选项的ModelForm

2024-09-22 14:20:37 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的应用程序中,我有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)
            )

这是将相关对象附加到窗体的安全且合理的方法吗?我担心在尝试创建分配时会丢失StrataLevel之间的连接。这是不是在视图中执行得更好


Tags: nameselffieldsmodelmodelslevellengthmax