Clone wiki

django-paramfield / Home

Django ParamField

What it is

Django ParamField is a model field for storing key-value data with not unique keys. I used it in a very old project and found it quite useful back then, so i decided to publish it. The code is a bit of a mess, though, but it's very usable.

How to use it

Just import ParamField and use it like a normal model field:

from paramfield import ParamField

    class Ball(models.Model):
        options = ParamField('Options')


For those, who want to know what's going on under the hood, I should mention ParamHolder. ParamHolder is a class that represents ParamField outside of the database, in python (that means, that you use ParamField for declaration in your model, but when you edit this model field, you actually work with ParamHolder, not ParamField itself)

Serialized values are stored in the TextField in the database like that:


Working with the field example

>>> from paramfield import ParamHolder

Creating an empty ParamHolder object (there will be one in your model already if you declared a ParamField)

>>> a = ParamHolder()
>>> a.params

Let's add some parameters

>>> a.add_param_value('tag', 'python')
>>> a.add_param_value('tag', 'c++')
>>> a.add_param_value('color', 'blue')
>>> a.add_param_value('color', 'red')
>>> a.add_param_value('color', 'green')

Let's have a look at them

>>> a.params
{u'color': [u'blue', u'red', u'green'], u'tag': [u'python', u'c++']}
>>> a.get_param_values('color')
[u'blue', u'red', u'green']
>>> a.get_param_names()
[u'color', u'tag']
>>> a.has_param('tag')
>>> a.param_has_value('tag', 'c++')

Let's remove a value for a param

>>> a.remove_param_value('tag', 'c++')
>>> a.param_has_value('tag', 'c++')

Let's remove a parameter itself:

>>> a.remove_param('tag')
>>> a.has_param('tag')
>>> a.params
{u'color': [u'blue', u'red', u'green']}

What is it all good for?

Well, in an old project we used this field for caching some calculations, many-to-many parameters, tags and breadcrumb-paths, so there would be less queries to the database and they would be less complex. We also used it to quickly filter through a lot of cached many-to-many params and to store some miscelanous data.

You can also search the database for parameters like that:

>>> Ball.objects.filter(options__icontains=";color:red;")

I hope this project will be useful for you.


Check out the download section