如何正确存储 HStore 字段?

How to store HStore field properly?

这里我有一个 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,l:Large,

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'}