如何验证object.create()方法的选择? [英] How to validate CHOICES for objects.create() method?
问题描述
我有以下模型:
from django.db import models
class Artist(models.Model):
TYPE_CHOICES = (
('Person', 'Person'),
('Group', 'Group'),
('Other', 'Other'),)
name = models.CharField(max_length=100)
type = models.CharField(max_length=20, choices=TYPE_CHOICES)
问题是,如果我创建这样的对象: Artist.objects.create(...)
类型验证无效.我该如何激活验证?
The problem is that if I create an object like this:
Artist.objects.create(...)
the type validation doesn't work.
How can I activate the validation for this?
推荐答案
您可以创建一个(抽象的)模型,该模型首先执行验证,然后使用以下方法保存对象:
You can make an (abstract) model that first performs validations before saving the object with:
class ValidatedModel(models.Model):
class Meta:
abstract = True
def save(self, *args, **kwargs):
self.clean_fields() # validate individual fields
self.clean() # validate constraints between fields
self.validate_unique() # validate uniqness of fields
return super(ValidatedModel, self).save(*args, **kwargs)
然后例如在以下模型中使用它:
and then for example use this in models like:
class Artist(ValidatedModel):
TYPE_CHOICES = (
('Person', 'Person'),
('Group', 'Group'),
('Other', 'Other'),)
name = models.CharField(max_length=100)
type = models.CharField(max_length=20, choices=TYPE_CHOICES)
请注意,如果您调用 .save()
方法(或某些其他函数执行此操作),则上述内容将验证模型对象,但是某些方法会规避调用 .save()的情况.
方法,例如 Model.objects.bulk_create(..)
等.
Note that the above will validate model object in case you call the .save()
method (or some other function does that), but some methods circumvent calling the .save()
method like Model.objects.bulk_create(..)
, etc.
这篇关于如何验证object.create()方法的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!