Opened 10 years ago
Last modified 8 years ago
#22741 closed Bug
Makemigrations fails when using lambda as default for ForeignKey field — at Initial Version
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
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.