How to store a dictionary on a Django Model?

前端 未结 13 916
广开言路
广开言路 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条回答
  •  -上瘾入骨i
    2020-11-29 00:21

    As Ned answered, you won't be able to query "some data" if you use the dictionary approach.

    If you still need to store dictionaries then the best approach, by far, is the PickleField class documented in Marty Alchin's new book Pro Django. This method uses Python class properties to pickle/unpickle a python object, only on demand, that is stored in a model field.

    The basics of this approach is to use django's contibute_to_class method to dynamically add a new field to your model and uses getattr/setattr to do the serializing on demand.

    One of the few online examples I could find that is similar is this definition of a JSONField.

提交回复
热议问题