Trying to create migration for a GeneratedField yields attribute error

I have a model that looks like this

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

class Artwork(models.Model):
    title = models.CharField(max_length=60)
    title_length = models.GeneratedField(
        expression=Length(F('title')),
        output_field=models.PositiveSmallIntegerField(),
        db_persist=False
    )

When I try to create a new migration to add title_length to an existing model, I get this output:

  File "/vnv/django_static_sites_shared_3_13/lib/python3.13/site-packages/django/db/models/fields/generated.py", line 58, in generated_sql
    resolved_expression = self.expression.resolve_expression(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'resolve_expression'

I’m not sure if I am just doing it wrong, or if getting the length of a CharField is not something I am allowed to do with a GeneratedField.

Thank you for any insight.

You are using the Expressions wrong, Check Func out.

Thanks, I went to implement what you suggested, saw that it still didn’t work, and then just nuked my database and existing migrations and started over.

Then it worked. So then I wondered if my original way would also work without a database and migrations existing, and it worked too.

I guess whatever the problem actually was, it was more related to me already having a database with existing migrations and data. So it’s a mystery.

Thank you nevertheless.