Django 2.2 CheckContraint: how to check "min_foo < max_foo" ?

19 views
Skip to first unread message

Olivier

unread,
Nov 12, 2019, 12:15:42 PM11/12/19
to Django users
hello,

Looking at [1], I can see examples where one can check at database level, that a model field min_foo satisfies a constraint such as "min_foo > 5".
How do you write a constraint involving two different fields like  "min_foo < max_foo" or "discounted_price < price" ?

PostgreSQL doc shows how to write such constraint but how to express those with Django 2.2 ?


Best regards

Leonardo Rezende

unread,
Nov 13, 2019, 7:35:37 AM11/13/19
to django...@googlegroups.com
Hi,
   Didn't tested... Did you try the F expression?

from django.db import models

class Customer(models.Model):
    age = models.IntegerField()

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(discounted_price__lte=models.F('price')), name='age_gte_18'),
        ]

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/43d1b1aa-9261-4ebc-b54f-761959c01c31%40googlegroups.com.


--
--

Leonardo Rezende

Olivier

unread,
Nov 13, 2019, 8:00:57 AM11/13/19
to Django users
Yes, using things like models.F('price') made it !

Thank you very much, Leonardo, for this.


Le mercredi 13 novembre 2019 13:35:37 UTC+1, LRezende a écrit :
Hi,
   Didn't tested... Did you try the F expression?

from django.db import models

class Customer(models.Model):
    age = models.IntegerField()

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(discounted_price__lte=models.F('price')), name='age_gte_18'),
        ]

Em ter., 12 de nov. de 2019 às 14:14, Olivier <oza...@gmail.com> escreveu:
hello,

Looking at [1], I can see examples where one can check at database level, that a model field min_foo satisfies a constraint such as "min_foo > 5".
How do you write a constraint involving two different fields like  "min_foo < max_foo" or "discounted_price < price" ?

PostgreSQL doc shows how to write such constraint but how to express those with Django 2.2 ?


Best regards

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django...@googlegroups.com.


--
--

Leonardo Rezende
Reply all
Reply to author
Forward
0 new messages