fopina / django-bulk-update-or-create

`bulk_update_or_create` for Django model managers
MIT License
148 stars 16 forks source link

duplicate key value violates unique constraint #27

Open pbeneteau opened 3 years ago

pbeneteau commented 3 years ago

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?

fopina commented 3 years ago

Not really if you're using only id as match_field but also have a unique constraint on another field

pbeneteau commented 3 years ago

Why can't I use the primary key 'id' as the match_field? I have no unique_together fields.

pbeneteau commented 3 years ago

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']
fopina commented 3 years ago

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?

pbeneteau commented 3 years ago

Yeah sorry just renamed it... its MyModel instead.

Yeah I've check that already, no duplicates.

fopina commented 3 years ago

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

fopina commented 1 year ago

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)