如何在Django模型的EmailField中添加多个电子邮件?

epggiuax  于 2023-04-07  发布在  Go
关注(0)|答案(2)|浏览(125)

我正在尝试创建一个Client模型,其中的电子邮件字段可以包含一个或多个电子邮件地址。
我知道EmailField类型接受单个电子邮件地址,但在我的例子中,我需要扩展它以接受多个电子邮件地址:

class Client(models.Model):
    company_name = models.CharField(max_length=100, unique=True)
    project = models.ForeignKey(Project, blank=True, null=True,
        on_delete=models.SET_NULL)
    email_list = models.EmailField(max_length=70)

如何实现这一点,以扩展多个电子邮件地址的email_list容量?

rryofs0p

rryofs0p1#

EmailField不能用于列表。
您可以创建另一个模型并使用ForeignKey

class Client(models.Model):
    company_name = models.CharField(max_length=100, unique=True)
    project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.SET_NULL)

class Email(models.Model):
    client = models.ForeignKey(Client on_delete=models.CASCADE)
    email_list = models.EmailField(max_length=70)

或者像这样的CharField:

class Client(models.Model):
    company_name = models.CharField(max_length=100, unique=True)
    project = models.ForeignKey(Project, blank=True, null=True, on_delete=models.SET_NULL)
    email_list = models.CharField(max_length=1000)

Client.objects.create(company_name="test", project=project_instance, email_list=json.dumps(email_list))

但是第二个,我认为,是不好的,你会失去EmailField验证。

fcwjkofz

fcwjkofz2#

使用文本字段

class Client(models.Model):
        bcc = models.TextField(null=True, blank=True)

输入多封邮件(密送字段):test1@example.com,test2@example.com

from django.core.mail import EmailMessage

clients= Client.objects.all()
for client in clients:
    subject = client.subject
    content = client.body
    contact_email = client.msg_from
    to = client.msg_to
    bcc_mails = client.bcc
    bcc = bcc_mails.split(",")
    bcc_mails.replace('"', "")
    email = EmailMessage(
        subject,
        content,
        contact_email,
        [to],
        bcc,
        headers={'Reply-To': contact_email}
    )

相关问题