【问题标题】:Access many2many field values before saving to database in clean method django在干净的方法 django 中保存到数据库之前访问 many2many 字段值
【发布时间】:2017-11-01 10:10:38
【问题描述】:

我有以下模型,我正在尝试根据 many2many 字段的值在 clean 方法中引发验证错误

RULE_SET_CHOICES = (
    ('G', 'GLOBAL'),
    ('C', 'LOCAL')
)

class Books(models.Model):
    type = models.CharField(max_length=2, choices=RULE_SET_CHOICES, null=False, default='C')
    author = models.ManyToManyField(Author, related_name="books", blank=True, null=True)

    def clean(self):
        if self.type = 'G':
            // Check if type is Global and if we tried to associate / add authors  then raise a validation error 
            if self.author :
                raise ValidationError("When type is global, you should not associate authors")

但是当我尝试访问self.author 时,我遇到了以下错误

*** ValueError: "<Books: Hello World- G>" needs to have a value for field "author " before this many-to-many relationship can be used

那么有没有办法在保存到数据库之前访问多对多关系字段值?因为我需要根据上面的值引发验证错误

【问题讨论】:

    标签: django django-models many-to-many


    【解决方案1】:

    如果您使用模型表单进行验证,您可以访问self.cleaned_data 中的表单字段。

    我不知道有什么方法可以检查模型的 clean 方法中的值。在访问多对多字段之前,您需要检查 self.pk

    def clean(self):
        if self.pk and self.type = 'G':
            ...
    

    请注意,self.author 是相关经理,因此if self.author 将始终为真。也许你想要self.author.exists()。由于可以有多个作者,最好将字段命名为authors

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 2020-06-23
      • 2014-06-15
      • 2016-06-29
      相关资源
      最近更新 更多