
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Making a Pickle field in Django models
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)>]>
- Related Articles
- Adding JSON field in Django models
- Exporting models data in Django
- Implementing models reversion in Django
- Importing data into models in Django
- Making a URL shortner app in Django
- Django – Making a Django website more human-like using Humanizer
- Making a simple counter app using request.session in Django
- How to add a Money field in Django?
- How to make a Country field in Django?
- Making your own custom filter tags in Django
- How to add a text editor field in Django?
- Add the slug field inside Django Model
- Making an existing field Unique in MySQL?
- Django – Making a contact form and storing its data without model, query and html
- Python object serialization (Pickle)
