[Django]-Python Pickle object in Django model

3👍

You can use BinaryField to store pickled object.

From comments of the question, you can also use JSONField to store dict from class instance. You can do it like this:

from django.contrib.postgres.fields import JSONField

class YourModel(models.Model):
    data = JSONField()

Lets say you have a class like this(which you want to store):

class YourClass(object):
    a = None
    b = None
    c = None

    def __str__(self):
        return 'Your Class: {}, {}, {}'.format(self.a, self.b, self.c)

Now you can generate dictionary like this:

some_instance = YourClass(a=1, b=2, c=3)
cls_dict = some_instance.__dict__
print(cls_dict)
# {'a': 1, 'b': 2, 'c': 3}

y = YourModel(data=cls_dict)
y.save()

Now you can try restoring Class instance from dictionary like this:

y = YourModel.objects.first()
some_instance = YourClass()
some_instance.__dict__.update(y.data)

print(some_instance)

# 'Your Class: 1, 2, 3'
👤ruddra

0👍

I will not comment on wether or not it’s wise to use pickled data in the database. But you can use the django-picklefield library to store pickled data:

https://pypi.org/project/django-picklefield/

👤Azer

Leave a comment