如果给定的电子邮件已经在数据库中,但允许空值,我正在寻找单行过滤器查询。
forms.py
def clean_email(self):
email = self.cleaned_data.get('email')
q = Email.objects.filter(email=email)
if not email or q.count() == 0:
return email
raise forms.ValidationError('Podany email już widnieje w bazie')
models.py
class Email(models.Model):
person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE)
email = models.EmailField(max_length=70, blank=True)
答案 0 :(得分:0)
您可以为此写validator
:
from django.core.exceptions import ValidationError
def validate_email(value):
q = Email.objects.filter(email=value)
if not q.exists():
return email
raise ValidationError('Podany email już widnieje w bazie')
forms.py
:
from django import forms
class EmailForm(forms.ModelForm):
email = forms.EmailField(required=True, validators=[validate_email])
models.py
:
from django.db import models
class Email(models.Model):
person = models.ForeignKey(Person, editable=False, on_delete=models.CASCADE)
email = models.EmailField(max_length=70, blank=True, validators=[validate_email])
答案 1 :(得分:0)
您可以使用exists()
Email.objects.filter(email=email).exists()
返回True
是找到一个实例。