0

Note in my model contact_email is my primary key for the Contact model

I have an html page and form where users can upload an excel file to upload their contacts to the database. If contact_email has not been uploaded previously, everything works fine, and contacts are uploaded.

However, if the contact_email already exists an error is thrown and contact's info is not updated, for example if in new excel file an existing contact's fav_sport has changed it will not update.

Error given is IntegrityError at /upload/ duplicate key value violates unique constraint "contacts_contact_pkey" DETAIL: Key (contact_email)=(john@gmail.com) already exists.

Here is the code causing the error:

for index, row in df.iterrows():
    created = Contact.objects.update_or_create(
        contact_name = row[0],
        fav_sport = row[1],
        contact_email = row[2],
    )

How can this code be modified to resolve this error?

Padoga
  • 495
  • 3
  • 18

2 Answers2

1

You are using all fields for uniqueness query in update_or_create as in documentation

( assuming you want to update by contact_email )

for index, row in df.iterrows():
    created = Contact.objects.update_or_create(
        contact_email= row[2],
        defaults = {
            "contact_name": row[0],
            "fav_sport": row[1]
        }
    )
iklinac
  • 14,944
  • 4
  • 28
  • 30
-1

The defaults is a dictionary of (field, value) pairs used to update the object.

try this and let me know if it works:

for index, row in df.iterrows():
    defaults = {
        "contact_name": row[0],
        "fav_sport": row[1],
        "contact_email": row[2],
    }
    obj, created = Contact.objects.update_or_create(**defaults, defaults=defaults)
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33
  • Issue is with primary key -> your recommendation does not solve anything. Please reread my question. – Padoga Mar 08 '20 at 04:59