ValueError: Cannot serialize function: lambda while using makemigrations

django cannot serialize
django cannot serialize arbitrary class instances
django cannot serialize nested classes
django migrations
django reverse migration
django models
django model fields
django custom migration

When I do python manage.py makemigrations, i get above error and I am unsure where the error is happening. I saw some post regarding this issue but i find mainly in DateTimeField() where the function was passed but in my case I have used auto_now attribute instead of some datetime related function.

However, I have used lambda function in the class method as follow.

@classmethod
    def get_content_models(cls):
        """
        Return all Package subclasses.
        """
        is_content_model = lambda m: m is not Package and issubclass(m, Package)


def set_helpers(self, context):
    current_package_id = getattr(current_package, "id", None)
    current_parent_id = getattr(current_package, "parent_id", None)
    self.is_current_child = self.parent_id == current_package_id
    self.is_child = self.is_current_child

    def is_c_or_a(package_id):
        parent_id = context.get("_parent_package_ids", {}).get(package_id)
        return self.id == package_id or (parent_id and is_c_or_a(parent_id))
    self.is_current_or_ascendant = lambda: bool(is_c_or_a(current_package_id))

I am not clear on this issue, So i have posted for understanding the cause. Is above code creating that issue? If it is the cause, what should be done instead?

I don't know where exactly this issue lies in the models so here is the detail of models.py of package app in gist because the code is a bit huge . It is not reached to booking models so I am only putting the code of package app and here it is

https://gist.github.com/SanskarSans/51d2f287309a97163e680cc38abd3e06

UPDATE

In my Package models, I have used the custom field and in that field there was the use of lambda instead of callable function and that was creating an issue. Due to the long file of models, I did not paste it here, I apologize for that.

Here what I had done

in_menus = MenusField(_("Show in menus"), blank=True, null=True)

class MenusField(MultiChoiceField):
    """
    ``MultiChoiceField`` for specifying which menus a package should
    appear in.
    """

    def __init__(self, *args, **kwargs):
        choices = [t[:2] for t in getattr(settings, "PAGE_MENU_TEMPLATES", [])]
        default = getattr(settings, "PAGE_MENU_TEMPLATES_DEFAULT", None)
        if default is None:
            default = [t[0] for t in choices]
        elif not default:
            default = None
        if isinstance(default, (tuple, list)):
            d = tuple(default)
            # this lambda should be avoided
            # default = lambda:d 
            default = default_value(d)
        defaults = {"max_length": 100, "choices": choices, "default": default}
        defaults.update(kwargs)
        super(MenusField, self).__init__(*args, **defaults)

An example replacing the lambda with a function.

Borken version:

class SomeModel(ParentModel):
    thing_to_export = ArrayField(models.CharField(max_length=50), 
                                 default=lambda: ['Default thing'])

Working version:

def default_thing():
    return ['THIS IS A DEFAULT']

class SomeModel(ParentModel):
    thing_to_export = ArrayField(models.CharField(max_length=50), 
                                 default=default_thing)

Cannot serialize function: lambda on running migrations · Issue , When I type: python3.4 manage.py makemigrations It stops with ValueError: Cannot serialize function: lambda Backstory: I'm trying to run  When I type: python3.4 manage.py makemigrations It stops with ValueError: Cannot serialize function: lambda Backstory: I'm trying to run xml2sqlite.py to build the test suite files (#322). After we switched to Python 3.4 I started gettin

I assume you are using the pickle module for serialization.

You cannot pickle the class in which set_helpers is defined. That method sets self.is_current_or_ascendant to a lambda function, and those are on the list of things that cannot be pickled (see 12.1.4 in https://docs.python.org/3/library/pickle.html).

The class method cannot be a problem since it only defines one local variable, is_content_model, which immediately goes out of scope and gets deleted. In fact that method, as you presented it here, does nothing at all.

#22892 (ValueError: Cannot serialize function: lambda) – Django, to create a pull request. Description ¶. I can't make migrations. More info here: ​https://dpaste.de/J476 I think it's release blocker because of I can't use  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

The follows might be helpful to others in the future.

It worked to change the lambda expression into a function.

The following square_root and square_root_lambda worked the same:

def square_root(x):
    return math.sqrt(x)

square_root_lambda = lambda x: math.sqrt(x)


print(square_root(4))
print(square_root_lambda(4))

#22351 (Remove suggestion of using lambdas in model field , But Django's migrations cannot cope with lambdas passed as keyword line 303, in serialize raise ValueError("Cannot serialize function: lambda") ValueError​:  end of the traceback before the change: /local/lib/python2.7/site-packages/django/db/migrations/writer.py", line 415, in serialize raise ValueError("Cannot

Makemigrations fails when a lambda is used, When an autoslug field is defined with a lambda the makemigrations command fails. ValueError: Cannot serialize function: lambda  ValueError: Cannot serialize function: lambda while using makemigrations python django python-3.x django-models asked Apr 4 '18 at 4:46 stackoverflow.com

Migrations, There are several commands which you will use to interact with migrations and in the app (i.e. if it has no dependencies on any other migration in the same app). True are serialized in migrations, so the functions and classes will need to be Nested classes; Arbitrary class instances (e.g. MyClass(4.3, 5.7) ); Lambdas  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:

writer.py, __init__) # See if this operation is in django.db.migrations. It converts timezone​-aware values to utc with an 'executable' utc representation of tzinfo. __name​__ == '<lambda>': raise ValueError("Cannot serialize function: lambda") if value. limit_choices_to = lambda: {'pub_date lte': datetime.date.utcnow()} But Django's migrations cannot cope with lambdas passed as keyword arguments, so that fact either should be mentioned in the docs (let examples use named functions rather than lambdas) or community has to put extra attention on migrations+lambdas problem.

Comments
  • This is the correct solution, but something is worth pointing out: you'll need to keep this function around forever, or at least as long as it is referenced in any migration files, because the migration file will want to import it.
  • so how do i solve the issue of ValueError: Cannot serialize function: lambda while using makemigrations?
  • Here is my model and I am using mezzanine gist.github.com/SanskarSans/51d2f287309a97163e680cc38abd3e06