11from datetime import datetime
22
3- from django .db import models
3+ from django .db import models , transaction
44from entity .models import Entity
55from entity_event .models import Event
66import uuid
@@ -26,6 +26,41 @@ def create_email(self, recipients=None, **kwargs):
2626 email .save ()
2727 return email
2828
29+ @transaction .atomic
30+ def create_emails (self , email_params_list ):
31+ """
32+ :param email_params_list: A list of dicts containing the keys for the create_email method
33+ :return: list of Email objects that were created
34+ """
35+ emails_to_create = []
36+ recipient_entities_per_email = []
37+
38+ # Build the emails to create and keep track of recipients
39+ for kwargs in email_params_list :
40+ scheduled = kwargs .pop ('scheduled' , datetime .utcnow ())
41+ recipients = kwargs .pop ('recipients' , [])
42+ emails_to_create .append (Email (scheduled = scheduled , ** kwargs ))
43+ recipient_entities_per_email .append (recipients )
44+
45+ # Bulk create the emails
46+ emails = Email .objects .bulk_create (emails_to_create )
47+
48+ # Build list of recipient through relationships to create
49+ recipients_to_create = []
50+ for i , recipient_entities in enumerate (recipient_entities_per_email ):
51+ for recipient_entity in recipient_entities :
52+ recipients_to_create .append (
53+ Email .recipients .through (
54+ email_id = emails [i ].id ,
55+ entity_id = recipient_entity .id ,
56+ )
57+ )
58+
59+ # Bulk create the recipient relationships
60+ Email .recipients .through .objects .bulk_create (recipients_to_create )
61+
62+ return emails
63+
2964
3065class Email (models .Model ):
3166 """Save an Email object and it is sent automagically!
0 commit comments