[Django]-Using Django's memcache API on Dynamically created models

1👍

I am aware of the problem where pickle can’t store a generated or dynamic class. I solved this by rigging in my dynamic type into the modules dict like so:

new_class = type(name, (models.Model,), attrs)
mod = sys.modules[new_class.__module__]
mod.__dict__[new_class.__name__] = new_class

It’s FAR from a clean or elegant solution, so if someone can think of a more django-friendly way to make this happen, I am all ears. However, the above code does work.

0👍

The reason there aren’t answers for this is because the answer is likely hackish. I don’t think you can unpickle an object in Python without knowing the structure of the class on the receiving end without some sort of hackish solution. A big reason pickle doesn’t support it is probably because it’s a fantastic way to introduce malicious code into your application.

http://www.mofeel.net/871-comp-lang-python/2898.aspx explains a bit why dynamically created classes can’t be unpickled.

In every case, I’ve either just serialized a dictionary of the attributes of the object using the dict method, or just figured out some awful work around. I hope you come up with something better.

Good Luck!

Leave a comment