python - 如何正确存储 HStore 字段?

标签 python django django-models django-views django-postgresql

我这里有一个 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'}

关于python - 如何正确存储 HStore 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64158124/

相关文章:

python - uWSGI 闲置后不重启

python - ast 模块使用什么类型的树遍历?

python - Django 用户经过身份验证(未经过身份验证)

python - 如何升级 django 项目的多个版本(1.8 到 1.11+)?

django - prefetch_related() 的无效参数

python - 无法安装 python-setuptools : ./configure: 没有这样的文件或目录

python - 未知标签类型 : continuous

django - “GenericRelatedObjectManager”不是 JSON 可序列化的

python - 如何在 django-rest-framework 中设置权限,以便 session 用户只能列出具有该用户外键的对象?

python - Django唯一关系不是唯一表