Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I define a check constraint on a string length (Django)

I am looking to do the following:

 constraints = [models.CheckConstraint(check=Length('code')==5, name='code_length')]

It fails because the check argument needs to be a
A Q object or boolean Expression that specifies the check you want the constraint to enforce

I’m not seeing string length field lookup nor am I seeing a way to incorporate the Length database function into a Q object argument. The only other option is a boolean expression (which is what I aimed at in my failed attempt above) but apparently this is an API that I have to implement.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am new to Django and would appreciate the help.

>Solution :

You can register the Length on a CharField:

from django.db.models import CharField
from django.db.models.functions import Length

CharField.register_lookup(Length)

and then define the constraint with the registered __length lookup:

from django.db import models
from django.db.models import Q

class SomeModel(models.Model):
    # …
    
    class Meta:
        constraints = [
            models.CheckConstraint(check=Q(code__length=5), name='code_length')
        ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading