I have a models in Django currently and I have made a field unique=True
so that no duplicates are submitted to the database. My problem is that it extends to all users. By this I mean that User 1 should be able to submit "Example1" and "Example2" and should never be able to submit "Example1" or "Example2" again and then User2 should come along and also be able to submit "Example1" and "Example2" but they cant because User 1 already submitted it.
Is there a way where I can get somewhat of a unique=True
but separately for each user and not just conjoined like it is now.
Thanks in advance. Code Below.
The problem resides in type =
and my users are being defined by ForeignKey also.
class Field_Repo1(models.Model):
user = models.ForeignKey(User, default=True, related_name="Field_Repo1", on_delete=models.PROTECT)
title = models.CharField(max_length=20, verbose_name='Title of Field')
type = models.CharField(max_length=200, blank=True, unique=True, null=True, verbose_name='Field')
class Meta:
ordering = ['-type']
def __str__(self):
return str(self.user) or 'NONE'
def get_absolute_url(self):
return reverse('repo1')
UPDATED CODE THAT WORKS
class Field_Repo1(models.Model):
user = models.ForeignKey(User, default=True, related_name="Field_Repo1", on_delete=models.PROTECT)
title = models.CharField(max_length=20, verbose_name='Title of Field')
type = models.CharField(max_length=22, choices=FIELDS, verbose_name='Field')
class Meta:
ordering = ['-type']
constraints = [
models.UniqueConstraint(fields=['user', 'type'], name='unique type for each user')
]
def __str__(self):
return str(self.user) or 'NONE'
def get_absolute_url(self):
return reverse('repo1')
CodePudding user response:
You need to use UniqueConstraint
:
class Field_Repo1(models.Model):
user = models.ForeignKey(User, default=True, related_name="Field_Repo1", on_delete=models.PROTECT)
title = models.CharField(max_length=20, verbose_name='Title of Field')
type = models.CharField(max_length=200, blank=True, unique=True, null=True, verbose_name='Field')
def __str__(self):
return str(self.user) or 'NONE'
def get_absolute_url(self):
return reverse('repo1')
class Meta:
ordering = ['-type']
constraints = [
models.UniqueConstraint(fields=['user', 'title'], name='unique title for each user')
]