Serializing cool methods in Django 1.7

When I try to run manage.py makemigrations in Django 1.7, I get the following error:

 ValueError: Cannot serialize: <bound method ModelBase.get_default of <class 'printapp.models.JobConfiguration'>> There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/dev/topics/migrations/#migration-serializing 

So it looks like there is a problem with the get_default method, which is defined in JobConfiguration , the definition of which is repeated below:

 @classmethod def get_default(cls): result = cls() result.save() return result 

After the link that was provided in the error message , it seems that serialization of the "class reference" is a supported function.

Is the "class reference" the same as @classmethod ?

How do I put a "class reference" in a "module top-level area"?

Why should methods be tracked by migrations? I was on the assumption that migrations are for database schemas that track only the data type, not the type of methods used by the class.

It is interesting to note: changing the definition of get_default to a static method, as repeated below, solves the problem, but at the cost of having to hardcode the JobConfiguration classname.

 @staticmethod def get_default(): result = JobConfiguration() result.save() return result 

(In some context: this method is referred to as JobConfiguration.get_default from within models.OneToOneField(JobConfiguration, default=JobConfiguration.get_default) with the effect of creating a new JobConfiguration for each of the fields created.)

+5
source share
1 answer

Migrations are just Python files that contain old definitions of your models - so in order to write them, Django must take the current state of your models and serialize them into a file.

classmethod is associated with the class. As the decorator wraps the method, the serializer is confronted with the ambiguity of what needs to be connected: a wrapper or a metosome, and it fails. There is no such problem with the static method, because it is a simple function attached to a class.

0
source

Source: https://habr.com/ru/post/1203026/


All Articles