Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2197

DB level constraints to validate 1 field against another one in Django

Is it any way to use Django constraint in model (models.CheckConstraint class) in order to create a constraint to validate value of one field against another one?

For example:

class Season(models.Model):
last_watched_episode = models.PositiveSmallIntegerField(
    null=True,
)
number_of_episodes = models.PositiveSmallIntegerField(

)

In this case I need to make a constraint that would raise an error in case value of the last_watched_episode field is greater then number_of_episodes field. 9 > 8 for example. Plus in case if last_watched_episode is Null(none) constrain should be omitted ( cant compare Null and int)

I have model and serializer validators already but goal is to create DB level constraints. Way to create it with RAW SQL and custom migration is also possible but via DJANGO constraints would be preferable. Thank you. DB -postgres 12

Upvotes: 1

Views: 281

Answers (1)

Aleksei Khatkevich
Aleksei Khatkevich

Reputation: 2197

Found that it is possible o use Fin constraints:

    class Meta:
        constraints = [
           models.CheckConstraint(name='mutual_watched_episode_and_number_of_episodes_check',
check = (models.Q(number_of_episodes__gte=models.F('last_watched_episode')))
            ),
        ]

This way it works

Upvotes: 2

Related Questions