2
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.

1 Answer 1

5

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']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.