我有联系人和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`))')有什么解决办法吗?
发布于 2015-01-12 13:51:37
也许这能帮上忙,最后把一行改为:
bulk_through.append(ThroughModel(contactgroup_id=gr.pk, contacts_id=item.pk))在我看来变量是混合的。
https://stackoverflow.com/questions/27896662
复制相似问题