'Tortoise ORM: blank = False. How to prevent the use of empty strings

My tortoise ORM model:

class User(Model):
    id = fields.IntField(pk=True)
    email = fields.CharField(100, unique=True, index=True)
    password = fields.CharField(128)
    name = fields.CharField(50)
    surname = fields.CharField(50)

The fields can't be null, but when I creating an object with the data like:

User.objects.create(email='', name='', ...)

It still works, and creates objects with empty values. That also works with the orm pydantic schemas.
In Django there's the blank property for that.

How to fix it?



Solution 1:[1]

Either write a custom validator:

from tortoise.validators import Validator
from tortoise.exceptions import ValidationError

class EmptyStringValidator(Validator):
    """
    Validate whether a string is empty.
    """
    def __call__(self, value: str):
        if not value:
            raise ValidationError(f"Value can not be empty")

class TestModel(Model):
    test_field = fields.CharField(max_length=100, null=True, validators=[EmptyStringValidator()])

Or use the built in tortoise.validators.MinLengthValidator:

class TestModel(Model):
    test_field = fields.CharField(max_length=100, null=True, validators=[MinLengthValidator(1)])

See docs: https://tortoise-orm.readthedocs.io/en/latest/validators.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MagneticSoil