[Django]-Django bulk create ignore duplicates

19👍

The ignore_conflicts parameter was added into bulk_create(Django 2.2)

and you can also find it in https://github.com/django/django/search?q=ignore_conflicts&unscoped_q=ignore_conflicts

6👍

This function will do it.
Note: this will work only if you have unique pk and don’t have anything else unique.

def insert_many(model, my_objects):
    # list of ids where pk is unique
    in_db_ids = model.__class__.objects.values_list(model.__class__._meta.pk.name)
    if not in_db_ids:
        # nothing exists, save time and bulk_create
        model.__class__.objects.bulk_create(my_objects)
    else:
        in_db_ids_list = [elem[0] for elem in in_db_ids]

        to_insert = []
        for elem in my_objects:
            if elem.pk not in in_db_ids_list and elem.pk not in to_insert:
                to_insert.append(elem)
        if to_insert:
            model.__class__.objects.bulk_create(to_insert)

How to use insert_many(MyModel(), list_of_myModels_defined_but_not_saved)

Leave a comment