【发布时间】: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