在 Django 中批量创建具有多对多关系的对象

Bulk Create objects with Many to Many Relationship in Django

我有Contacts和ContactsGroup两个模型

联系人包含组作为 m2m 关系

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

联系人是另一个模型

我想创建 bulk_create 联系人,其中 contact_group 也已添加到模型中。

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)

但是显示错误

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`))')

有什么解决办法吗?

也许这会有所帮助,请将最后一行更改为:

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

在我看来,变量是混合的。