我该如何“挑剔"?可以将数据库中Django模型的实例转换为示例python代码,我可以用来加载示例数据吗?

问题描述:

如何将数据库中的Django模型实例刺入"示例python代码,以用于加载示例数据?

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

我要:
1)快照一下我为Dj​​ango项目存储在MySQL数据库中的几百条记录
2)拍摄此快照并修改其中的数据(删除名称)
3)将此数据转换为腌制字符串"或实际的python代码,可用于将数据加载到新的用户帐户中.

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.

我要实现的主要功能是选择我当前的活动Django网站用户之一,将他们的某些数据复制并匿名化,然后将其作为示例数据加载给网站的所有新用户,以便他们可以使用这些数据可以帮助您学习系统.

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.

要将模型存储为字典,可以使用内置的Django函数:

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=[])

一旦将实例转换为字典并删除了必要的内容,只需使用常规的pickle.dumpspickle.loads方法来存储和检索数据.要使用该字典创建新的模型实例,您可以执行以下操作:

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()