如何正确存储HStore字段?

问题描述

这里有一个HStoreField,它将从用户输入中获取

用户s:Small,l:Large,格式提供输入,但是我认为HStoreField需要像这样的数据类型{'s': 'Small','l':'Large'}

如何将用户数据转换为这种格式,以便可以存储到HStoreField中。

或者只是我需要存储数据。我该怎么办?

class MyModel(models.Model):
      properties = HStoreField()

# view 
properties = request.POST.get('properties')
print(properties)

#properties has data in this format s:Small,MyModel.objects.create(properties=properties)

我得到这样的错误

django.db.utils.InternalError: Unexpected end of string
LINE 1: ...antity_reserved") VALUES ('ttt',11,'ttt','55','Small:rrr...

解决方法

您可以解析属性字符串并从中创建字典:

properties = 's:Small,l:Large,'

properties_dict = {}
for pair in properties[:-1].split(','):
    key,value = pair.split(':')
    properties_dict[key] = value

>>> print(properties_dict)
{'s': 'Small','l':'Large'}