Django 上需要的模型字段

Django 上需要的模型字段,django,Django,我想更改model clean()方法中字段的“required”属性 这是我的模型: class SomeModel(models.Model): type = models.CharField() attr1 = models.ForeignKey(Attr1, blank=True, null=True) attrs2 = models.ForeignKey(Attr2, blank=True, null=True) 现在,我在我的ModelForm\uuuu i

我想更改model clean()方法中字段的“required”属性

这是我的模型:

class SomeModel(models.Model):
    type = models.CharField()
    attr1 = models.ForeignKey(Attr1, blank=True, null=True)
    attrs2 = models.ForeignKey(Attr2, blank=True, null=True)
现在,我在我的ModelForm
\uuuu init\uuu
中通过从视图中添加一个新参数来实现这一点。 它动态设置字段的必填项

我能在我的模型中实现同样的效果吗?我正在使用django rest framework for API(它使用的是一个ModelForm),因此将运行
full_clean()
(其中包括
clean_fields()
clean()

假设如果类型以字符串开头,则需要attr1/attr2字段

我知道我可以在
Model.clean()
中执行此检查,但它将进入
非字段错误中

def clean(self):
    if self.type.startswith("somestring"):
        if self.attr1 is None and self.attr2 is None:
            raise ValidationError("attr1 and attr2 are required..")

我宁愿看到这些错误以简单的“This field is required”(标准的“required”django error)附在attr1和attr2字段错误上。

下面是一个代码示例,对我来说很好:

def clean(self):
        is_current = self.cleaned_data.get('is_current',False)
        if not is_current:
            start_date = self.cleaned_data.get('start_date', False)
            end_date   = self.cleaned_data.get('end_date', False)
            if start_date and end_date and start_date >= end_date:
                self._errors['start_date'] = ValidationError(_('Start date should be before end date.')).messages
        else:
            self.cleaned_data['end_date']=None
        return self.cleaned_data
看这里