I want to have a method to somehow show an error/prompt to the front end (could be json response), whenever user tries to add an object, in my case, 1 user cannot have more than 50 tasks stored inside the db, my db model is simple, it's just a task model, and a user model, each task has a foreign key user_id. I was doing it in golang-gorm using hooks, is there any similar method in Django to do so efficiently?
CodePudding user response:
You can override the clean method of your Task
model in order to raise a ValidationError
if the related user already has 50 tasks.
Something like this :
class Task(models.Model):
user = models.ForeyKey(User, on_delete=models.CASCADE, related_name='tasks')
def clean(self):
if self.user.tasks.count() >= 50:
raise ValidationError('User cannot have more than 50 tasks')