Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am trying to enforce a constraint upon a
Vote
model in my Django application, namely that a user cannot vote more than once the same object.
To do so I am using
unique_together
:
class Vote(models.Model):
vote = models.SmallIntegerField(choices=VOTES, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE,
related_name="user_votes")
definition = models.ForeignKey(Definition, on_delete=models.CASCADE,
related_name="definition_votes")
class Meta:
# Ensure user cannot vote more than once.
unique_together = ["user", "definition"]
This works, I think.
However, in Django's documentation for unique_together
it is noted that
UniqueConstraint
provides more functionality than
unique_together
. unique_together
may be deprecated in the future.
How can I substitute the above code using unique_together
with code using UniqueConstraint
?
The biggest confusion is the UniqueConstraint
documentation can be arrived at directly from unique_togther
, but it skips the Metas.constraint documentation:
constraints
Options.constraints
A list of constraints that you want to define on the model:
from django.db import models
class Customer(models.Model):
age = models.IntegerField()
class Meta:
constraints = [
models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
The sample code quickly tells you how to use the constraints.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.