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!
You can use get_or_create
.
s, created = Subject.objects.get_or_create(name="A new subject")
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)
`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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With