How to store a dictionary on a Django Model

This tutorial is all about how to use a dictionary model in Django which is easy and also helpful when you want to work with a dictionary. You might be thinking what is the task, it is so easy, you just need to add Dictionary Field in Django. But dear coders, there is no field as such and also there is nothing impossible to create in coding. Today we will be able to achieve this task by some other methods which will be proved so helpful.

Method 1 to store dictionary using container

We will try to create two models which will be a container class and an instance for the other. We will use a container class that will save the name and the other will be a class of key and value pairs that will take a value of existing containers. Then we will link key-value pairs to the containers.

Let’s start without any further delay.

Start your project and your app then quickly open your models.py, create two classes as mentioned above-

class Dicty(models.Model):
    name      = models.CharField(max_length=70)
    def __str__(self):
        return self.name

class KeyVal(models.Model):
    container = models.ForeignKey(Dicty,on_delete=models.CASCADE, db_index=True)
    key       = models.CharField(max_length=200, db_index=True)
    value     = models.CharField(max_length=200, db_index=True)
    def __str__(self):
        return self.container

You might be able to easily understand the above code. The first class contains the name of the container and the second class named Dicty contains container which is foreign to this model.

The next step is to register your model inside admin.py file using

from yourapp.models import Dicty, KeyVal

# Register your models here.
admin.site.register(Dicty)
admin.site.register(KeyVal)

You need to mention your app name inside your settings.py file-

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'yourappname',
]

Create a superuser using command linepython manage.py createsuperuser

Enter your details which will be later used to log in to Django administration.

Now, its time to migrate the changes made in the model so without any further interruption let’s migrate our model as-

python manage.py makemigrations

python manage.py migrate

Let’s run our server using the command python manage.py runserver

Navigate to the URL given or click on http://127.0.0.1:8000/

You will need to go to the admin section inside it so click on http://127.0.0.1:8000/admin/

Login using the same credentials you have created then you will be able to see browser window something like-

store a dictionary on a Django Model

Method 2 to store dictionary using picklefield

There is also one of the methods used pickled object method to complete this task. This field allows us to use pickleable objects. For this, you need to install django-pickleobject using pip install django-picklefield

Then you can edit your models.py as-

from django.db import models
from picklefield.fields import PickledObjectField

class someObject(models.Model):
    arguments=PickledObjectField()
    def __str__(self):
        return self.arguments

object=someObject()
object.arguments=['fancy', {'objects': 'inside'}]
object.save()

In this way, you can create your model and all other steps are as mentioned above.

You can also visit the official repository of the pickle field for more knowledge. Here’s the link- https://pypi.org/project/django-picklefield/

I hope you found this tutorial helpful, feel free to reach out and comment.

Leave a Reply

Your email address will not be published.