Saving an unknown object type into database in Dja

2019-08-29 13:22发布

问题:

I have the following model:

class Parameter(models.Model):
    par_type = = models.CharField(max_length=30)
    value = models.TextField()

Majority of the time the value field will store a number (value=3.2118). But sometimes I want to assign a list of other object IDs (like value="[32, 22, 45]") or a string object (like value="pass"), etc. I will use value field in functions like the ones below based on the value of par_type:

def foo(par): # par is a Parameter object.
    return float(par.value) / 2

def bar(par):
    # Some code to convert a par to a list of objects
    object_list = get_objects(par) 
    # Return a random object from list
    return random.choice(object_list)

I don't want to write a piece of code for every possible object type. Ideally there is one decompose() function to use everywhere. I thought of saving object as pickle or JSON type (saw it from here). But I couldn't figured out how to do it. I'm using MySQL db.

回答1:

You can try like this using BinaryField:

import pickle

class Parameter(models.Model):
    _value = models.BinaryField()

    def set_data(self, data):
        self._value = pickle.dumps(data)

    def get_data(self):
        return pickle.loads(self._value)

    value = property(get_data, set_data)

Usage:

In: b = Foo.objects.create(value=1)

In: b.value
Out: 1

In: b = Foo.objects.create(value={1:1,2:2})

In: b.value
Out: {1: 1, 2: 2}

In: b = Foo.objects.create(value=[1,1])

In: b.value
Out: [1, 1]

FYI, you can't store pass because it is not a Python Object, but its part of syntax. Instead of pass, consider using None.