Home > other >  don't let user create multiple objects with same value
don't let user create multiple objects with same value

Time:02-01

I have a model with a foreign key called "title". I want to restrict each user to only be able to create an object with each title once, so that they can't have multiple objects with the same title. Does anybody know how I can achieve this?

I have tried to add "unique_together" like this in my model but it does not work.

class Meta:
    unique_together = ('user', 'title')

CodePudding user response:

You can check if an object with same user and title exists already:

if YourModel.objects.filter(user=..., title= ....):
     .... here is the error handling ...
else:
     .... save object
  •  Tags:  
  • Related