モデルの clean() メソッドのフィールドの「必須」プロパティを変更したいと考えています。
これが私のモデルです:
class SomeModel(models.Model):
type = models.CharField()
attr1 = models.ForeignKey(Attr1, blank=True, null=True)
attrs2 = models.ForeignKey(Attr2, blank=True, null=True)
__init__
現在、ビューから新しいパラメーターを追加して、ModelForm でこれを行っています。フィールドの必須を動的に設定します。
私のモデルで同じことを達成できますか? 私はAPIにdjango-rest-frameworkを使用しています(ModelFormを使用しています)ので、 (とfull_clean()
を含む)が実行されます。clean_fields()
clean()
type が何らかの文字列で始まる場合、attr1/attr2 フィールドが必要だとします。
このチェックインを実行できることはわかっていますが、Model.clean()
その時点で着陸しNON_FIELD_ERRORS
ます。
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..")
attr1 および attr2 フィールド エラーに関連付けられたこれらのエラーを、単純な「このフィールドは必須です」(標準の「必須」django エラー) で表示したいと思います。