1

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

任务模型

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

这里是扩展 Task 的 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'

但不起作用。

总结:这是正确的吗?我应该对表单使用继承吗?而且,我怎样才能排除字段和其他参数,继承?

4

2 回答 2

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')
于 2013-05-24T13:12:01.787 回答
1

如果你想利用excludefrom TaskForminHumanTaskForm并扩展它,你可以从 TaskForm 继承 Meta 类:

class HumanTaskForm(TaskForm):
    class Meta(TaskForm.Meta):
        model = HumanTask
        exclude = TaskForm.Meta.exclude + ('uuid',)
于 2013-05-24T13:10:32.833 回答