Constrains
This is an additional option within the Meta class, utilized for establishing certain constraints on the model. Implementing the unique=True
option on a field effectively acts as a constraint.
UniqueConstraint
Ensures that the combination of specified field values is unique across the database table.
python99123456789101112from django.db import modelsfrom django.db.models import UniqueConstraintclass Book(models.Model):title = models.CharField(max_length=100)genre = models.ForeignKey(Genre, on_delete=models.CASCADE)author = models.ForeignKey(Author, on_delete=models.CASCADE)class Meta:constraints = [UniqueConstraint(fields=["title", "genre"], name="unique_book_titles_per_genre")]
In this example, the UniqueConstraint
ensures that no two books in the same genre have the same title.
CheckConstraint
Ensures that certain conditions hold true for the data in the database.
Suppose you want to ensure that the author's age is always greater than 18.
python9912345678910from django.db.models import CheckConstraint, Qclass Author(models.Model):name = models.CharField(max_length=100)age = models.IntegerField()class Meta:constraints = [CheckConstraint(check=Q(age__gt=18), name="age_greater_than_18")]
1. What is the purpose of the unique attribute in a Django model field?
2. What is the primary use of UniqueConstraint in Django's Meta class?
3. What does CheckConstraint do in Django models?
War alles klar?
Danke für Ihr Feedback!
Abschnitt 6. Kapitel 2
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen