首页 文章

django模型 - 有条件地设置空白=真

提问于
浏览
1

我正在尝试构建一个应用程序,用户可以自定义表单 . 以下示例包含用于创建由管理员使用的字段( QuestionFieldAnswerField )和由用户填写的 BoolAnswer 的类:管理员可以创建包含问题和可能答案的表单 .

根据django文档, blank=True 与评估有关 . 问题是它是在类级别而不是在对象级别上设置的 .

如何根据相关模型设置 blank=True ,以便我不必重新实现自己的验证器? (参见 BoolAnswer 中的伪代码)

我的 models.py

class QuestionField(models.Model):
    question = models.TextField(max_length=200)
    models.ForeignKey(Sheet)


class BoolAnswerField(AnswerField):
    question = models.ForeignKey(models.Model)
    if_true_field = models.TextField(max_length=100, null=True)


class BoolAnswer(models.Model):
    bool_answer_field = models.ForeignKey(BoolAnswerField)
    result = models.BooleanField()
    if_true = models.TextField(max_length=100, null=True,

                               blank=True if self.bool_answer_field.if_true_field)

简短说明:如果对 BoolAnswerField 问题的答案为真, if_true 字段应说明,为什么

1 回答

  • 3

    不要讨厌我,但验证是要走的路,请参阅here

    class BoolAnswer(models.Model):
        bool_answer_field = models.ForeignKey(BoolAnswerField)
        result = models.BooleanField()
        if_true = models.TextField(max_length=100, null=True, blank=True)
    
        def clean(self)
            if self.bool_answer_field.if_true_field and not self.if_true:
                raise ValidationError('BAF is True without a reason')
    

相关问题