How do I "pickle" instances of Django models in a database into sample python code I can use to load sample data?
I want to:
1) Take a snapshot of several hundred records that I have stored in a MySQL database for a Django project
2) Take this snapshot and modify the data in it (blanking out names)
3) Transform this data into a "pickled string" or actual python code that I can use to load the data into a new users account.
The main feature I'm trying to implement is to select one of my current active Django website users , copy and anonymize some of their data, and then load that as sample data for all new users of the website so they can use that data to help learn the system.
An easy way to do that would be to convert the model to a dict. Then, you can trivially pickle that and then re-inflate it to create new model instances.
To store the model as a dict, you can use a built-in Django function:
Once you've converted the instance to a dict and redacted what's necessary, just use the normal
pickle.dumps
andpickle.loads
methods to store and retrieve the data. To create a new model instance using that dict, you can do something like: