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

时间:2015-01-12 06:45:52

标签: django bulkinsert django-orm

我有联系人和联系人组两个模型

联系人包含组作为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`))')

有没有解决方案?

1 个答案:

答案 0 :(得分:3)

也许这可以提供帮助,最后改为一行:

bulk_through.append(ThroughModel(contactgroup_id=gr.pk, contacts_id=item.pk))
在我看来,变量是混合的。