首页 > 解决方案 > 如何正确存储 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,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...

标签: pythondjangodjango-modelsdjango-viewsdjango-postgresql

解决方案


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

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

推荐阅读