[Django]-Update_or_create wont respect unique key

61👍

There are two parts to update_or_create(): the filter values to select an object, and the update values that are actually updated. The keywords filter the object to update, the defaults are the values that are updated. If there is no match for the filters, a new object is created.

Right now you’re filtering on all of these values, since they’re all provided as keyword arguments:

upc = upc,
product_title = product_title,
is_buyable = is_buyable,
price = price,
image_url = image_url,
breadcrumb = breadcrumb,
product_url = product_url

The IntegrityError means that, even though that specific value for upc exists, an object matching all of these filters does not exist. Django then tries to create the object instead, but the upc is not unique, so this causes an IntegrityError.

If you filter on just the upc, that field will never cause an IntegrityError to be raised: either an existing object is found and updated, or a new object is created, but the value for upc is unique.

So to fix this, simply do:

obj, created = sfs_upcs.objects.update_or_create(
    # filter on the unique value of `upc`
    upc=upc,
    # update these fields, or create a new object with these values
    defaults={
        'product_title': product_title, 'is_buyable': is_buyable,  'price': price, 
        'image_url': image_url, 'breadcrumb': breadcrumb, 'product_url': product_url,
    }
)
👤knbk

Leave a comment