4

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

Sashko Lykhenko
  • 1,554
  • 4
  • 20
  • 36
  • Not an answer, but you absolutely definitely don't want to have those two default values in the method definition: see [this question](http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument). – Daniel Roseman Nov 20 '14 at 09:19
  • Django's orm is more of a database abstraction layer than an object persistence layer.. – thebjorn Nov 20 '14 at 09:25

1 Answers1

3

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.

Ian Price
  • 7,416
  • 2
  • 23
  • 34