在Django中批量创建具有多对多关系的对象 [英] Bulk Create objects with Many to Many Relationship in Django

查看:311
本文介绍了在Django中批量创建具有多对多关系的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Contacts和ContactsGroup两个模型

I have Contacts and ContactsGroup Two models

联系人包含作为m2m关系的组

contact contains group as m2m relationship

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

联系人是另一种模型

我想在模型上也添加了contact_group的情况下创建bulk_create联系人。

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)

但是显示错误

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 ?

推荐答案

也许可以帮上忙,最后将一行更改为:

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.

这篇关于在Django中批量创建具有多对多关系的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆