python - 如何正确存储 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...
解决方案
您可以解析属性字符串并从中创建字典:
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'}
推荐阅读
- android - 在颤动中隐藏后退按钮
- c++ - “架构 x86_64 的未定义符号” Xcode
- blockchain - 为什么coinbase官方库python和nodejs在github中被弃用了?
- bash - 在 Mac 上为目录创建快捷方式
- c# - Unity - 2D Top-Down 播放器奇怪地旋转以面对鼠标
- scala - 从 Hive 元存储(parquet 格式)在 Spark 中本地处理 10 亿条记录需要 6 个小时。如何加快速度?
- kubernetes - Kubernetes 有状态集 - 将现有 ID 映射到持久/有状态 pod
- java - Spring Data GemFire - 引起:java.lang.IllegalStateException:连接池“DEFAULT”尚未创建
- bash - 通过 vi 在编辑器中编辑命令行时,这是 bash 中的错误,还是预期的行为?
- php - Laravel 附加访问器意外地也添加了与响应的关系