How can I ignore inserting a duplicate in Django?

  Kiến thức lập trình

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?

1

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT