Sashko Lykhenko
Sashko Lykhenko

Reputation: 1664

How to store python objects with complex data fields in data base in Django?

I have a python class with comlex data structures. It has nested lists and dicts of objects and plain data.

class NK_Automata(object):
    def __init__(self,p_N=5,p_K=5,p_functionsList=None,p_linksList=None):
        self.N=p_N
        self.K=p_K

        if p_functionsList==None:
            p_functionsList=[]
        else:
            self.functionsList= p_functionsList   #list of BinFunction objects

        if p_linksList==None:
            self.linksList=[]
        else:
            self.linksList=p_linksList            #list of lists of integers

        self.ordinalNumber=-1


        self.stateSpan={}                     #stateSpan: {currentStateNumber: nextStateNumber,...}
        self.stateList=[]                     #list of integers
        self.attractorDict={}                 #attractorDict: {attractorNumber:[size,basinSize],...}

        self.attractorStatesDict ={}          #attractorStatesDict: {attractorStateNumber:[nextAttractorStateNumber,attractorStateWeight],...}

How should I store it in data base (sqlite3)? How to make a Django model for this object? Should I serialize the object?

Upd Fixed default parameters as suggested

Upvotes: 4

Views: 2311

Answers (1)

Ian Price
Ian Price

Reputation: 7616

You may want to look at django-picklefield.

django-picklefield provides an implementation of a pickled object field. Such fields can contain any picklable objects.

Basically, this will take any Python object, save a pickled representation of it, and you can re-create it as the same exact object after pulling the pickled representation right out of the database.

You may want to create a model object NK_Automata that stores each of those attributes in a picklefield, then create a method to recreate the actual class object w/ all attributes. I can't assure you that the full class would be picklable, but it may ever be possible to store the whole NK_Automata class instance in a field.

Upvotes: 3

Related Questions