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...
If True, this field must be unique throughout the table. This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.