How can I “saw” Django model instances in a database into python code example that I can use to load sample data?

How do I “saw” Django model instances in a database into sample python code that I can use to load sample data?

I want:
1) Take a snapshot of several hundred records that I saved in the MySQL database for the Django project

2) Take this snapshot and change the data in it (name blanking)
3) Convert this data to a “pickled string” or the actual python code, which I can use to upload data to a new user account.

The main function that I am trying to implement is to select one of my active users of the Django website, copy and anonymize some of my data, and then upload it as sample data for all new website users so that they can use this data will help to study the system.

+5
source share
2 answers

An easy way to do this is to convert the model to a dict. Then you can trivially pickle it and then re-inflate it to create new instances of the model.

To save the model as a dict, you can use the built-in Django function:

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

dict , , pickle.dumps pickle.loads . dict, - :

my_instance = MyModel(**my_dict)
#add any customization for the new instance here
my_instance.save()
+11

Django 1.8 , , :

my_dict = dict([(f.attname, getattr(instance, f.attname))
               for f in instance._meta.get_fields()
               if hasattr(f, 'attname')])
+1

All Articles