1

Let's say there's a model with unique constraint:

class A(models.Model):
    my_unique_value = models.CharField(unique=True)

I want to bulk_create As, but some of the my_unique_value values I'm inserting are already in the db. I want them to be ignored (not inserted).

What is the best, most efficient way to achieve that? I cannot insert them one by one, and catch Exceptions (it's too slow). I also cannot fetch all As to clean duplicates first.

The underlying DB is postgres.

Matt
  • 163
  • 3
  • 13

1 Answers1

-3

You can use get_or_create, which as it names says - will only create if the item doesn't exist, otherwise it will fetch it. You can discard the fetched item.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284