How to store a dictionary on a Django Model?

If it’s really dictionary like arbitrary data you’re looking for you can probably use a two-level setup with one model that’s a container and another model that’s key-value pairs. You’d create an instance of the container, create each of the key-value instances, and associate the set of key-value instances with the container instance. Something like:

class Dicty(models.Model):
    name      = models.CharField(max_length=50)

class KeyVal(models.Model):
    container = models.ForeignKey(Dicty, db_index=True)
    key       = models.CharField(max_length=240, db_index=True)
    value     = models.CharField(max_length=240, db_index=True)

It’s not pretty, but it’ll let you access/search the innards of the dictionary using the DB whereas a pickle/serialize solution will not.

Leave a Comment