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

后端 未结 2 416
轻奢々
轻奢々 2021-02-06 09:43

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

相关标签:
2条回答
  • 2021-02-06 10:15

    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()
    
    0 讨论(0)
  • 2021-02-06 10:36

    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')])
    
    0 讨论(0)
提交回复
热议问题