Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate entries with Django and Postgresql

One of my views has the task of inserting several values into my database. I was under the impression that if I set up my model with unique vendor_names:

class Page(models.Model):
  vendor_name = models.CharField(max_length=128, unique=True)
  website = models.CharField(max_length=128)
  food_type = models.CharField(max_length=128)
  img_url = models.CharField(max_length=128)

that if I did:

  for vendor in vendors:
    c = Page(vendor_name=vendor["name"], 
             website=vendor["link"], 
             food_type=vendor["type"],
             img_url=vendor["imageurl"])
    c.save()

The appearance of duplicates would be skipped over and I would only have one copy in the database. At least thats what I understood from here. Instead of this do I have to add an if statement thats checks my database for each entry and sees if it currently is in there, if it isn't insert otherwise skip. Or am I missing something here? Whats the purpose of the unique constraint? Is it just to throw an error when there is a duplicate? Could I maybe exploit this instead?

The error I get is

Exception Value: duplicate key value violates unique constraint...
like image 981
theamateurdataanalyst Avatar asked Sep 06 '25 03:09

theamateurdataanalyst


1 Answers

In Django, unique enforces a database level validation of entries so if you add that property to your model's field after the table was already created, the unique condition will not be added to your table even if you do syncdb later at some point.

If you don't want to create rows with same vendor_name, you should use Page.objects.get_or_crate to let Django create Page object with that vendor name only if not exists:

for vendor in vendors:
    page, created = Page.objects.get_or_create(
        vendor_name=vendor['name'], 
        defaults={'website': vendor['link'], 
                  'food_type': vendor['type'], 
                  'img_url': vendor['imageurl'])

    if created:
        print('Page created: ', page)
like image 72
Ozgur Vatansever Avatar answered Sep 07 '25 19:09

Ozgur Vatansever