Duplicate entries with Django and Postgresql

One of my views has a task to insert multiple values ​​into my database. I was under the impression that if I set up my model with unique vendor_name

s:

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)

      

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 occurrence of duplicates will be skipped and I will only have one copy in the database. At least that's what I understood from here . Instead, I have to add an if statement that checks my database for each record and sees if it is currently in if it is not inserted otherwise. Or am I missing something? What is the purpose of a unique constraint? Is it just a mistake when there is a duplicate? Can I use this instead?

The error I am getting is

Exception Value: duplicate key value violates unique constraint...

      

+3


source to share


2 answers


Django unique

provides data validation at the database level, so if you add this property to a model field after the table has already been created, the unique condition will not be added to your table, even if you do it syncdb

later at some point.

If you don't want to create lines with the same vendor_name

, you should use Page.objects.get_or_crate

to tell Django to create an object Page

with this provider name only if it doesn't exist:



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)

      

+2


source


You have unapplied migrations. The fact that you get Exception Value: duplicate key value violates unique constraint

means that you need to clean up duplicates from your database before applying migrations. You cannot just add constraints that are already broken.

If you select this option, delete the entire table from the database and retry the migration again. If this is not an option, you will need to remove duplicates and apply the migration afterwards.



It unique

won't work without migration .

0


source







All Articles