Reputation: 245
class User:
username = (unique=True)
class Object:
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = ()
How can i have multiple Objects with the same name, but each user can only have one unique Object name.
for example:
user1 can only have one unique Object name of "dog", user2 can also only have one unique Object name of "dog", therefore there can be multiple Objects with the same name of "dog", but each user can only have one Object named "dog" through the ForeignKey. if user1 try's to create another object named "dog" then raise something like a forms validation error.
Upvotes: 2
Views: 109
Reputation: 309109
You can use the unique_together
option to add the database constraint.
class MyModel(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
name = models.CharField(max_length=30)
class Meta:
unique_together = ['user', 'name']
Upvotes: 5