Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I ignore inserting a duplicate in Django?

I have some static tables that I’m initializing like this with a Management Command

Suit(name="Clubs").save()
Suit(name="Hearts").save()
Suit(name="Diamonds").save()
Suit(name="Spades").save()

I want to be able to re-run this anytime, in case there are new values, but I want to avoid inserting duplicates. The database has a Unique constaint, so if there are duplicates I’ll get an error.
Other than wrapping each individual statement in a try/catch, is there a way I can run several statements like this and ignore the Constraint Violation and keep going?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Either you can use the method @deceze, mentioned that is to use a list and try-except.

or you can use the get_or_create method

A convenience method for looking up an object with the given kwargs (may be empty if your model has defaults for all fields), creating one if necessary.

for ele in lst: # the list of data
    Suit.objects.get_or_create(ele)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading