[英]How to validate CHOICES for objects.create() method?
I have the following model:我有以下模型:
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)
The problem is that if I create an object like this: Artist.objects.create(...)
the type validation doesn't work.问题是,如果我创建这样的对象: Artist.objects.create(...)
类型验证不起作用。 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)
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.请注意,如果您调用.save()
方法(或其他一些函数这样做),上面将验证模型对象,但有些方法会绕过调用.save()
方法,如Model.objects.bulk_create(..)
等.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.