Opened 11 years ago

Closed 11 years ago

Last modified 8 years ago

#22741 closed Bug (needsinfo)

Migrate fails with `TypeError` when using a callable default for a `ForeignKey` — at Version 2

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

Description (last modified by Tim Graham)

When using a lambda function as a default value for a ForeignKey field, makemigrations will fail with the exception:

    ValueError: Cannot serialize function: lambda

This is the code:

    from django.db import models


    class House(models.Model):
        address = models.CharField(max_length=100)


    class Person(models.Model):
        house = models.ForeignKey(House, default=lambda: House.objects.all()[0])
        name = models.CharField(max_length=100)

I tried to change the lambda to a defined function like this:

    from django.db import models


    class House(models.Model):
        address = models.CharField(max_length=100)


    def first_house():
        House.objects.all()[0]


    class Person(models.Model):
        house = models.ForeignKey(House, default=first_house)
        name = models.CharField(max_length=100)

In this case, makemigrations works, but migrate will now fail, with the exception:

    TypeError: int() argument must be a string or a number, not 'House'

I'm testing this in Python 3 btw.

Change History (2)

comment:1 by Simon Charette, 11 years ago

Cc: Simon Charette added
Resolution: needsinfo
Status: newclosed
Summary: Makemigrations fails when using lambda as default for ForeignKey fieldMigrate fails with `TypeError` when using a callable default for a `ForeignKey`

Please use the preview options before submitting a ticket -- code blocks should be wrapped in {{{ }}} in order to be displayed properly.

Unfortunately the migration framework doesn't support lambdas deconstruction, see #21037 and #22351 for details.

Since you seems to have another issue setting default=first_house we'd need the full TypeError traceback to determine if it's actually a Django bug.

The fact that your first_house function doesn't return anything (copy-pasta from the lambda?) is a bit suspicious here.

comment:2 by Tim Graham, 10 years ago

Description: modified (diff)
Note: See TracTickets for help on using tickets.
Back to Top