#34288 closed Bug (duplicate)

Using queryset manager methods as default value breaks makemigrations

Reported by: Mikhail Podgurskiy Owned by: nobody
Component: Database layer (models, ORM) Version: 4.1
Severity: Normal Keywords: migrations
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When I'm using a manager method as default value for a model field, migrations can't be generated

class Company(models.Model):
    name = models.CharField(max_length=250)


class Client(models.Model):
    name = models.CharField(max_length=250)
    company = models.ForeignKey(
        Company,
        on_delete=models.DO_NOTHING,
        default=Company.objects.last
    )

django/db/migrations/serializer.py", line 169, in serialize
    raise ValueError(
ValueError: Could not find function last in django.db.models.manager.

Change History (1)

comment:1 by Mariusz Felisiak, 16 months ago

Component: MigrationsDatabase layer (models, ORM)
Resolution: duplicate
Status: newclosed

This was fixed in 46efd03d2674084051f7ce04006e95520649a1ac. However, as documented:

"The default can’t be a mutable object (model instance, list, set, etc.), ..."
"For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances."

so the default cannot be a model instance.

Duplicate of #33733.

Note: See TracTickets for help on using tickets.
Back to Top