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.

I am new to Django and would appreciate the help.


Solution 1:

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')
        ]