Pickle in Python is primarily used in serializing and deserializing a Python object structure. In other words, it's the process of converting a Python object into a byte stream to store it in a file/database, maintain program state across sessions, or transport data over the network
In this article, we are going to see how to make a Django field which will save pickle objects. We will only work with models.py and Django shell
First of all, install the django-picklefield package −
pip install django-picklefield
Example
In models.py −
from django.db import models from picklefield.fields import PickledObjectField # Create your models here. class new_model(models.Model): args = PickledObjectField()
Here, we created a model and added the pickle field.
Now let's check if it works or not. On the terminal run "python manage.py shell" and type the following −
from myapp.models import * obj=new_model(args=['fancy', {'objects': 'inside'}]).save() new_model.objects.all()
We run the shell and create a new model instance that can store pickle objects. Any object stored in it will be converted to a pickle object.
To save in models, you can write like this −
from django.http import HttpResponse def my_view(request): Object=new_model(args=['fancy',{'name': 'ath'}]) Object.save() return HttpResponse("Object saved")
You can add any pickle object or anything that can be pickeled in this field.
Output
In [4]: new_model.objects.all() Out[4]:<QuerySet [<new_model: new_model object (1)>]>