django - 从验证器访问模型实例

标签 django django-models

我将如何访问正在验证器中针对特定字段进行验证的模型实例?

模型.py

def question_instances(value):  #validator     
   # not sure how to get model instance within this function

   industry = model_instance.industry
   questions = Question.objects.filter(industry=industry)
   if questions.count() > 3:
      raise ValidationError('Too many questions for this industry')

class ExampleQuestion(models.Model):
    industry = models.ForeignKey(Industry, on_delete=models.CASCADE)    
    question = models.CharField(max_length=200, validators=[question_instances])

    def __str__(self):
        return self.industry.industryname

最佳答案

你不能。如果你需要这个,不要使用验证器;改用干净的功能。

class ExampleQuestion(models.Model):
    industry = models.ForeignKey(Industry, on_delete=models.CASCADE)    
    question = models.CharField(max_length=200)

    def clean(self):
         industry = self.industry
         questions = Question.objects.filter(industry=industry).exclude(pk=self.pk)
         if questions.count() > 3:
             raise ValidationError('Too many questions for this industry')

关于django - 从验证器访问模型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55081651/

相关文章:

python - 如何扩展用户模型以添加更多字段

python - 虚拟环境安装django后,仍然无法导入模块

python - 你如何找到一段 Python 的 CPU 消耗?

python - Django 中的 ViewDoesNotExist

mysql - MySQL 上嵌套原子 block 和并发进程的 Django 事务失败

django - 属性错误 : 'RelatedManager' object has no attribute 'remove'

Django collectstatic 从 Heroku 每次推送到 S3

javascript - 如何将 application/x-mpegURL 放入 videojs 的源中

mysql - 使用 Django dumpdata 转储整体数据的一个子集?

django - 博客中的类别。它们如何工作?