I have a JSONField that I need to apply a default dictionary to. As per the documentation, I am avoiding passing the mutable dictionary to the default field. This is done by instead passing the copy method to the default argument like such:
default_dict = {'some_key': 'some value'}
class MyModel(models.Model):
my_field = models.JSONField(default=default_dict.copy)
When applying makemigrations, this is failing because of the following condition in django.db.migrations.serializer.FunctionTypeSerializer:
if self.value.__module__ is None:
raise ValueError("Cannot serialize function %r: No module" % self.value)
I can get around this by defining a callable that returns a copy, but I think this is adding unnecessary syntax and makes it harder to read:
class ADict(dict):
def __call__(self):
return self.copy()
default_dict = ADict({'some_key': 'some value'})
class MyModel(models.Model):
my_field = models.JSONField(default=default_dict)
Is there a way to pass a built-in objects method as the default value for a Django field?
You can't do this since it basically needs to be a named function, whereas default_dict.copy
is an "anonymous" function.
You can however make a named function like:
default_dict = {'some_key': 'some value'}
def copy_default_dict():
return default_dict.copy()
class MyModel(models.Model):
my_field = models.JSONField(default=copy_default_dict)
or even simpler:
def copy_default_dict():
return {'some_key': 'some value'}
class MyModel(models.Model):
my_field = models.JSONField(default=copy_default_dict)