duplicate key value violates unique constraint
Opened this issue · 7 comments
I do this:
MyModel.objects.bulk_update_or_create(objs, ['name', 'slug', 'rank', 'symbol', 'is_active'], match_field='id')
and I get this error:
duplicate key value violates unique constraint "mymodel_pkey"
DETAIL: Key (id)=(1) already exists.
Very weird for a update or create right?
Not really if you're using only id
as match_field but also have a unique constraint on another field
Why can't I use the primary key 'id' as the match_field? I have no unique_together fields.
Here is my model:
class MyModel(models.Model):
"""Store information about an item"""
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=100)
slug = models.CharField(max_length=200)
symbol = models.CharField(max_length=40)
sign = models.CharField(max_length=5, blank=True, null=True)
rank = models.PositiveIntegerField(blank=True, null=True)
is_active = models.BooleanField(default=True)
last_updated = models.DateTimeField(auto_now=True, blank=True, null=True)
objects = BulkUpdateOrCreateQuerySet.as_manager()
class Meta:
db_table = "model"
ordering = ['rank']
Where does currency
come from?
Have you renamed to "MyModel" for posting purposes? Makes it harder to understand/help
Anyway, are you sure there's not multiple objs with id 1 in a single batch?
Yeah sorry just renamed it... its MyModel instead.
Yeah I've check that already, no duplicates.
If you're reading from a source where id is a string (instead of an int), cast it to int when assigning to the objs id/pk field.
I thought that had been fixed already but maybe not
Note to self: leaving this issue open to implement checks for these cases - DB type different than unsaved field type (setting to '1' and IntegerField returns 1 from DB)