假设您有一个简单的模型:
Class Contact(models.Model):
email = models.EmailField(max_length=70,blank=True)
first = models.CharField(max_length=25,blank=True)
last = models.CharField(max_length=25,blank=True)
我想做的是将电子邮件设置为唯一的,但是,这样做我必须排除空白电子邮件地址 - 我不希望这样。
我正在考虑这样的事情,但我想知道是否有更好的方法来处理它。
from django.core.validators import email_re
from django.core.exceptions import ValidationError
def save(self, *args, **kwargs):
# ... other things not important here
self.email = self.email.lower().strip() # Hopefully reduces junk to ""
if self.email != "": # If it's not blank
if not email_re.match(self.email) # If it's not an email address
raise ValidationError(u'%s is not an email address, dummy!' % self.email)
if Contact.objects.filter(email = self.email) # If it already exists
raise ValidationError(u'%s already exists in database, jerk' % self.email)
super(Contact, self).save(*args, **kwargs)
有一个更好的方法吗?