How to store a dictionary on a Django Model?

前端 未结 13 924
广开言路
广开言路 2020-11-28 23:24

I need to store some data in a Django model. These data are not equal to all instances of the model.

At first I thought about subclassing the model, but I’m trying t

13条回答
  •  借酒劲吻你
    2020-11-29 00:17

    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.

提交回复
热议问题