How do I "pickle" instances of Django models in a database into sample python code I can use to load sample data?
Asked Answered
A

2

8

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.

Aqaba answered 25/1, 2012 at 22:40 Comment(2)
This sounds pretty much like it... docs.djangoproject.com/en/dev/howto/initial-dataFaint
Django can export data in JSON. It's much, much easier to work with Django's own internal serialization. Why don't you simply want to use Python's dumpdata and loaddata built-in commands?Basanite
D
14

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:

from django.forms.models import model_to_dict
my_dict = model_to_dict(my_instance,fields=[],exclude=[])

Once you've converted the instance to a dict and redacted what's necessary, just use the normal pickle.dumps and pickle.loads methods to store and retrieve the data. To create a new model instance using that dict, you can do something like:

my_instance = MyModel(**my_dict)
#add any customization for the new instance here
my_instance.save()
Dreibund answered 25/1, 2012 at 23:30 Comment(1)
Be aware that you cannot create a new model from the dict if it contains foreign keys as it will raise a ValueErrorDefinitive
N
3

On Django version 1.8 and above, if your models has foreign keys, you can use:

my_dict = dict([(f.attname, getattr(instance, f.attname))
               for f in instance._meta.get_fields()
               if hasattr(f, 'attname')])
Nursling answered 5/8, 2015 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.