Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a unique value exists before creating it

When Django runs .save() on a primary key attribute, it first does a SELECT to see if it already exists, then decides whether to do an INSERT or an UPDATE. Is there a way to elegantly do the same for a unique but not primary key field?

Basically, if the model looks like this:

class Subject(models.Model):
    name = models.CharField(max_length=64, unique=True)

I would want to do the following without throwing an error

>>> s=Subject(name="A new subject")
>>> s.save()
>>> s
<Subject: A subject>
>>> s=Subject(name="A new subject")
>>> s.save()
--- django.db.utils.IntegrityError: column name is not unique

Inversely, I could make 'name' the pk, but I wasn't sure of an elegant Django way to make non-pk unique auto-incrementing ids.

Any help is appreciated. Thank you!

like image 719
Peter O Avatar asked May 08 '11 18:05

Peter O


3 Answers

You can use get_or_create.

s, created = Subject.objects.get_or_create(name="A new subject")
like image 59
Daniel Roseman Avatar answered Oct 17 '22 06:10

Daniel Roseman


You can override the save method on that model and check if the value you are trying to save already exists:

class Subject(models.Model):
     name = models.CharField(max_length=64, unique=True)

     def save(self, *args, **kwargs):
         #check if value exists / increment something etc

         #continue with save, if necessary:
         super(Subject, self).save(*args, **kwargs)
like image 33
Mihai Oprea Avatar answered Oct 17 '22 07:10

Mihai Oprea


`If you put unique=True in your model, when you try to create an object with same unique = True parameter, error will returned, so make sure that you call them in try-except to handle that.

like image 1
Sudeesh Avatar answered Oct 17 '22 05:10

Sudeesh