How to store a dictionary on a Django Model?

前端 未结 13 915
广开言路
广开言路 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:27

    If you don't need to query by any of this extra data, then you can store it as a serialized dictionary. Use repr to turn the dictionary into a string, and eval to turn the string back into a dictionary. Take care with eval that there's no user data in the dictionary, or use a safe_eval implementation.

    For example, in the create and update methods of your views, you can add:

    if isinstance(request.data, dict) == False:
        req_data = request.data.dict().copy()
    else:
        req_data = request.data.copy()
    
    dict_key = 'request_parameter_that_has_a_dict_inside'
    if dict_key in req_data.keys() and isinstance(req_data[dict_key], dict):
        req_data[dict_key] = repr(req_data[dict_key])
    
    0 讨论(0)
提交回复
热议问题