如何定义字符串长度的检查约束(Django)

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

我希望执行以下操作:

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

它失败了,因为 check 参数需要是 A Q object or boolean Expression that specifies the check you want the constraint to enforce

我没有看到必须实现的字符串长度 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

我是 Django 的新手,非常感谢您的帮助。

您可以在 CharField 上注册 Length:

from django.db.models import <strong>CharField</strong>
from django.db.models.functions import <strong>Length</strong>

<strong>CharField</strong>.register_lookup(<strong>Length</strong>)

然后使用注册的 __length 查找定义约束:

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

class SomeModel(models.Model):
    # …
    
    class Meta:
        constraints = [
            models.CheckConstraint(<strong>check=Q(code__length=5)</strong>, name='code_length')
        ]