0

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 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Worked great! Just to be clear on your last line, I was planning to set a string value like Foo.objects.create(value="pass") which worked fine. I believe you meant that I cannot do Foo.objects.create(value=pass)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.