Bulk Create objects with Many to Many Relationship

2020-04-17 06:25发布

I have Contacts and ContactsGroup Two models

contact contains group as m2m relationship

class ContactGroup(models.Model):
    contact_group   = models.ManyToManyField(ContactGroup, null=True, related_name="contact_list")

and contacts is another model

I want to create bulk_create contacts where contact_group also added on the model.

group_list = []

if group:
   groups = [item.strip() for item in group.split(',')]
   for item in groups:
     try:
        group, created = ContactGroup.objects.get_or_create(account=account, name=item)
        group_list.append(group)
     except :
        pass
contact = Contacts(
         name = name,
         phone = change_phone_format(phone),
         email = email,
         address = address,
         company = company,
         website = website,
         notes = notes,
         dob = dob,
         account = account
                )
bulk_obj.append(contact)
bulk_group.append(group_list)

ThroughModel = Contacts.contact_group.through

now_date = datetime.datetime.now()
Contacts.objects.bulk_create(bulk_obj)
contacts = Contacts.objects.filter(created_on__gte=now_date)
bulk_through = []
for i, item in enumerate(contacts):
    for gr in bulk_group[i]:
       if item and gr:
          bulk_through.append(ThroughModel(contactgroup_id=item.pk, contacts_id=gr.pk))
ThroughModel.objects.bulk_create(bulk_through)

But shows error

IntegrityError at /contact-manager/contacts/process/goIKlkpymfWCaFeiQXwp/

(1452, 'Cannot add or update a child row: a foreign key constraint fails (`sparrow`.`contactmanager_contacts_contact_group`, CONSTRAINT `D3781be41803f836ec292e41ed99c16a` FOREIGN KEY (`contactgroup_id`) REFERENCES `contactmanager_contactgroup` (`id`))')

Is there any solution ?

1条回答
贪生不怕死
2楼-- · 2020-04-17 07:03

Maybe this can help, change last but one line to:

bulk_through.append(ThroughModel(contactgroup_id=gr.pk, contacts_id=item.pk))

seems to me that variables are mixed.

查看更多
登录 后发表回答