不同型号的独特电子邮件
Unique email in different models
我有 2 个不同的模型,其中包含电子邮件字段:
class Model1(models.Model):
email = models.EmailFields(unique=True)
"""
other fileds
"""
class Model2(models.Model):
email = models.EmailFields(unique=True)
"""
other fileds
"""
这些模型不必包含相同的电子邮件。我怎样才能做到这一点?
在每个模型的每个 ModelForm
中使用 clean
方法:
class Model1Form(forms.ModelForm):
class Meta:
model = Model1
fields = ['email', ...]
def clean(self):
cleaned_data = super().clean()
email = self.cleaned_data.get('email')
if Model2.objects.filer(email=email).exists():
self.add_error('email', 'Email have to be unique')
和其他 ModelForms 一样?
您可以使用 multi-table inheritance。然后所有电子邮件将存储在一个 table 中,唯一约束将在数据库标签处处理。
BaseModel(models.Model):
email = models.EmailFields(unique=True)
class Model1(models.Model):
# other fields
class Model2(models.Model):
# other fields
如果您不想使用多table 继承,您将不得不手动检查另一个table。为了避免重复,也许你可以写一个基本模型形式class,然后class它。
我有 2 个不同的模型,其中包含电子邮件字段:
class Model1(models.Model):
email = models.EmailFields(unique=True)
"""
other fileds
"""
class Model2(models.Model):
email = models.EmailFields(unique=True)
"""
other fileds
"""
这些模型不必包含相同的电子邮件。我怎样才能做到这一点?
在每个模型的每个 ModelForm
中使用 clean
方法:
class Model1Form(forms.ModelForm):
class Meta:
model = Model1
fields = ['email', ...]
def clean(self):
cleaned_data = super().clean()
email = self.cleaned_data.get('email')
if Model2.objects.filer(email=email).exists():
self.add_error('email', 'Email have to be unique')
和其他 ModelForms 一样?
您可以使用 multi-table inheritance。然后所有电子邮件将存储在一个 table 中,唯一约束将在数据库标签处处理。
BaseModel(models.Model):
email = models.EmailFields(unique=True)
class Model1(models.Model):
# other fields
class Model2(models.Model):
# other fields
如果您不想使用多table 继承,您将不得不手动检查另一个table。为了避免重复,也许你可以写一个基本模型形式class,然后class它。