2

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 ?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
Bishnu Bhattarai
  • 2,800
  • 8
  • 36
  • 44
  • 1
    Never, ever, ever, ever do `except: pass`. That's terrible. Firstly you must never do a blank except anyway - only catch the exceptions you know you can deal with - and secondly you should never just silence them. – Daniel Roseman Jan 12 '15 at 09:40
  • `bulk_create()` returns the created objects, so you can save a db call and just do `contacts = Contacts.objects.bulk_create(bulk_obj)` – ygesher Mar 08 '16 at 08:48

1 Answers1

3

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.

var211
  • 596
  • 5
  • 10