代码之家  ›  专栏  ›  技术社区  ›  Marius

具有用户定义字段和外键选项的模型窗体

  •  1
  • Marius  · 技术社区  · 7 年前

    在我的应用程序中,我有 Study 作为中心模式。 书房 s有多个 Strata ,每个 地层 有多个 Level s、 用户创建 Allocation 选择一个级别进行研究 地层 与该研究相关,比如:

    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')
    

    为了为分配创建表单创建字段,我当前正在查找 地层 以及表单构造函数中的关联级别,但由于用户不与它们交互,因此隐藏了层:

    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)
                )
    

    这是将关联对象附加到表单的安全而合理的方法吗?我担心我会忘记 地层 水平 尝试创建分配时。这是不是在视野中表现得更好?

    0 回复  |  直到 7 年前