【问题标题】:How to store json in django mysql database by using python?如何使用python将json存储在django mysql数据库中?
【发布时间】:2014-01-24 01:34:03
【问题描述】:

故事背景:

我想使用 python 编程语言将 json 对象存储在 django mysql 数据库中。 但我得到了一个错误。

配置:

  • 操作系统:Ubuntu 12.04 64 位
  • 程序语言:python
  • 框架:django
  • 数据库:mysql
  • 需要存储的对象:json

代码参考:

json_objects={ u'name': u'REF_1', u'text': u'it is apple', u'time': u'20131210T120039Z'}

代码:

--> 模型.py

from django.db import models
class Messages(models.Model):
        id           = models.AutoField(primary_key=True)
        received     = models.DateTimeField(null=False)
        name         = models.TextField()
        data         = models.TextField()
        text         = models.TextField()
        word         = models.TextField()

        def __unicode__(self):
            return self.text

-->views.py

from threechannels.models import Messages
data_send_to_db=Messages.objects.create(received=datetime.strptime(json_objects["time"], "%Y%m%dT%H%M%SZ"),name=json_objects_post["name"],data=json_objects_dumps,text=json_objects["text"],word=related_words_hits)

我得到的错误:

DatabaseError: (1054, "'field list' 中的未知列 'data'")

如果我将 json_objects 更改为 objects=json.dumps(json_objects),我会遇到另一个错误:字符串索引必须是整数而不是字符串。我认为 json_objects_post["name"] 会导致这个问题。

任何提示??? 太感谢了。

【问题讨论】:

标签: python mysql django json


【解决方案1】:

对我来说,您的 json_objects 似乎是一个简单的 python 字典。所以这是一个有效的操作:

received=datetime.strptime(json_objects["time"], "%Y%m%dT%H%M%SZ")

但这个不是:

name=json_objects_post["name"]

我不确定你想用“_post”实现什么,但你可以按照它应该使用的方式使用 python 字典:

name=json_objects["name"]

也适用于其他字段:

data=json_objects

或

data=json.dumps(json_objects)

等等……

【讨论】:

    【解决方案2】:

    原代码:

    data_send_to_db=Messages.objects.create(received=datetime.strptime(json_objects["time"], "%Y%m%dT%H%M%SZ"),name=json_objects_post["name"],data=json_objects_dumps,text=json_objects["text"],word=related_words_hits)
    

    变化:

    data_send_to_db=Messages(received=datetime.strptime(json_objects["time"], "%Y%m%dT%H%M%SZ"),name=json_objects_post["name"],data=json_objects_dumps,text=json_objects["text"],word=related_words_hits)
    

    它的工作原理......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 2018-05-10
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2013-03-11
      相关资源
      最近更新 更多