模式继承如何实现模型表单(继承?)

时间:2013-05-24 10:00:26

标签: django django-models django-forms

我最近将我的数据库移动到模型继承结构。这是一个例子:

任务模型

STATUS_CHOISE = (('PR', 'In process'), ('ST', 'Stopped'), ('FN', 'Finished'), ('DL', 'Deleted'),)
class Task(models.Model):
    owner = models.ForeignKey(User)
    process = models.ForeignKey(Process)
    title = models.CharField(max_length=200, default='')
    description = models.CharField(max_length=1000, default='')
    date_created = models.TimeField(auto_now_add=True, auto_now=False) 
    date_deadline = models.DateTimeField(default=lambda: (datetime.now() + timedelta(days=7)), auto_now_add=False)
    parameters = jsonfield.JSONField()
    objects = InheritanceManager()
    status = models.CharField(max_length=2, choices=STATUS_CHOISE, default='ST')

这里是扩展任务的HumanTask

PLATFORMS = (('CC', 'CrowdComputer'), ('MT', 'Amazon Mechancial Turk'),)
class HumanTask(Task):
    number_of_instances = models.IntegerField(default=1)
    uuid = models.CharField(max_length=36, default='')
    page_url = models.URLField(max_length=400, default='', null=True, blank=True)
    platform = models.CharField(max_length=2,choices=PLATFORMS, default='CroCo')
    validation=models.OneToOneField(ValidationTask)
    reward = models.OneToOneField(Reward, null=True, blank=True)

现在,我该如何创建表单?我应该为这两个类使用ModelForm吗? 关键是:有些字段必须是exclude

例如,TaskForm是:

class TaskForm(ModelForm):
    owner = forms.ModelChoiceField(queryset=User.objects.all(),widget=forms.HiddenInput)
    process = forms.ModelChoiceField(queryset=Process.objects.all(),widget=forms.HiddenInput)

    class Meta:
        model = Task
        exclude = ('date_deadline', 'date_created','parameters','status','objects')

所以我想要的HumanTaskForm是排除是从TaskForm继承的 我试过这个

class HumanTaskForm(TaskForm):
    class Meta:
        model= HumanTask
        exclude = 'uuid'

但不起作用。

总结:这是对的吗?我应该为表格使用继承吗?并且,我如何排除字段和其他参数,继承?

2 个答案:

答案 0 :(得分:1)

如果您想利用excludeTaskForm的{​​{1}}并对其进行扩展,您可以从TaskForm继承Meta类:

HumanTaskForm

答案 1 :(得分:1)

您需要继承父Meta以及。

子类将继承/复制父Meta类。子元中显式设置的任何属性都将覆盖继承的版本。据我所知,无法扩展父元属性(即添加到'排除')。

class AwesomeForm(forms.ModelForm):
    class Meta:
        model = AwesomeModel
        exclude = ('title', )

class BrilliantForm(AwesomeForm)
    class Meta(AwesomeForm):
        model = BrilliantModel

print(AwesomeForm.Meta.model)
> AwesomeModel

print(BrilliantForm.Meta.model)
> BrilliantModel

print(AwesomeForm.Meta.exclude)
> ('title', )

print(BrilliantForm.Meta.exclude)
> ('title', )

你可以这样做:

class BrilliantForm(AwesomeForm)
    class Meta(AwesomeForm):
        model = BrilliantModel
        exclude = AwesomeForm.Meta.exclude + ('uuid', )

print(BrilliantForm.Meta.exclude)
> ('title', 'uuid')