2

デフォルトでは必須ではない特定のフィールドを作成するルールをDjangoモデルに追加するにはどうすればよいですか。別のフィールドが設定されている場合は必須です。またはその逆でも

このモデルがあるとしましょう:

class Item(models.Model):

    name = models.CharField(max_length = 75)
    cant_be_sold = models.BooleanField()
    flat_price = models.IntegerField(blank = True, null = True, default = None, validators = [MinValueValidator(0)])
    defense = models.IntegerField(blank = True, null = True, default = None, validators = [MinValueValidator(0)])
    required_classes = models.ManyToManyField('otherappname.Class', related_name = 'Requires_Classes', blank = True, null = True, default = None)

ここで 2 つの状況が考えられるとしましょう。

  1. 私は次のようにマークcant_be_soldTrueます; 現在、flat_price はNone( NULL)のみです
  2. 記入しdefenseます; 現在、1 つ以上を選択する必要がありますrequired_classes

Django でこれを行う良い方法は何でしょうか。私のシステムでは Item Variance が大幅に拡張されているため、私の Item モデルには 70 を超えるプロパティ フィールドがあるため、誤ったエントリを防ぐのに役立ちます。

4

1 に答える 1

4

cleanモデルのメソッドを記述します。その中で、フィールド値を変更し、検証エラーを発生させることができます。次の例から始めてください。

def clean(self):
    if self.cant_be_sold and self.flat_price is not None:
        raise ValidationError("flat_price must be None when cant_be_sold is True")
于 2013-07-20T13:34:36.860 に答える