14👍
Try the proper nested-tuple syntax ((foo,bar),)
instead of just (foo, bar)
?
https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together
27👍
As aganders3 mentions the constraint is enforced at the database level; I assume though that you are using a database like SQLite that doesn’t support this kind of constraint.
The reason that it all works as expected through the admin is that it is doing the uniqueness check itself (it doesn’t rely strictly on the database to signal constraint violations).
You can switch to a database engine that supports this kind of uniqueness constraint (either MySQL or Postgres would work) or you could look at adding the check in using signals: http://djangosnippets.org/snippets/1628/
- [Django]-Django : get_or_create Raises duplicate entry with together_unique
- [Django]-Jquery and Django CSRF Token
- [Django]-Redirect to Next after login in Django
8👍
Yes the paremeter unique_together receives as input a tuple of tuples, I have not tested tuples of more than two elements but it should work
for your example:
unique_together = (("teamID", "name"), ("slug", "teamNumber"))
or:
unique_together = (("teamID", "name", "slug", "teamNumber", "totalScore"))
- [Django]-In Django filter statement what's the difference between __exact and equal sign (=)?
- [Django]-Django: list all reverse relations of a model
- [Django]-How do I get the object if it exists, or None if it does not exist in Django?
2👍
I found this approach helpful without adding any unnecessary fields
class Request(models.Model):
user = models.ForeignKey(User, related_name='request_list', on_delete=models.CASCADE)
requested_user = models.ForeignKey(User, on_delete=models.CASCADE)
request_date = models.DateField(default=timezone.now())
request_status = models.BooleanField(default=False)
def save(self, *args, **kwargs):
# Checking for duplicate requests
try:
request = Request.objects.get(user=self.user, requested_user=self.requested_user)
raise ValidationError('Duplicate Value', code='invalid')
except self.DoesNotExist:
super().save(*args, **kwargs)
# Checking for reversed duplicate requests
try:
request_new = Request.objects.get(requested_user=self.user, user=self.requested_user)
raise ValidationError('Duplicate Value', code='invalid')
except self.DoesNotExist:
super().save(*args, **kwargs)
def __str__(self):
return self.user.username + '------>' + self.requested_user.username
- [Django]-How does pgBouncer help to speed up Django
- [Django]-Using IntellijIdea within an existing virtualenv
- [Django]-How do I keep my Django server running even after I close my ssh session?