29👍
✅
You can use get_or_create
.
s, created = Subject.objects.get_or_create(name="A new subject")
2👍
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)
- Registering Django system checks in AppConfig's ready() method
- How show personalized error with get_object_or_404
- What does it mean for an object to be unscriptable?
1👍
`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.
Source:stackexchange.com