#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 )
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 , 11 years ago
| Cc: | added | 
|---|---|
| Resolution: | → needsinfo | 
| Status: | new → closed | 
| Summary: | Makemigrations fails when using lambda as default for ForeignKey field → Migrate fails with `TypeError` when using a callable default for a `ForeignKey` | 
comment:2 by , 11 years ago
| Description: | modified (diff) | 
|---|
  Note:
 See   TracTickets
 for help on using tickets.
    
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_housewe'd need the fullTypeErrortraceback to determine if it's actually a Django bug.The fact that your
first_housefunction doesn't return anything (copy-pasta from thelambda?) is a bit suspicious here.