【问题标题】:Writing file line to Django model field将文件行写入 Django 模型字段
【发布时间】:2010-07-21 17:18:52
【问题描述】:

我似乎无法将文件中的一行写入 Django 模型的字段。该字段在模型中描述为:

 text = models.TextField(null=True, blank=True, help_text='A status message.')

但是,当我尝试创建一个新对象时,我无法使用 readline 函数填充此字段:

file = open(filename, 'r')
str = file.readline()

当我尝试将str 用于文本字段时,我似乎无法读取或写入数据库。我没有收到任何错误,所以我假设它是编码问题。有什么建议吗?谢谢。

编辑

数据库为postgres数据库,字段类型为“text”。

我用来创建对象的代码是:

Message.objects.create_message(sys, str)

def create_message(self, system, msg):
        """Create a message for the given system."""
        m = Message.objects.create(system=system,
                   text=msg)
        return m

【问题讨论】:

  • 你如何“使用 str 作为文本字段”?其他不起作用的代码在哪里?

标签: python database django file file-io


【解决方案1】:

不要创建与 python 内置类型冲突的变量名。 “str”为字符串类型。Python解释器:

>> str
<type 'str'>

【讨论】:

  • 谢谢,已更改,但问题仍然存在。
【解决方案2】:

我认为您没有正确调用 create_message 方法。你不应该这样称呼它吗

create_message(sys, str)

而不是这个

Message.objects.create_message(sys, str)

?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2012-03-27
    • 2019-01-01
    • 2012-09-27
    • 2019-06-30
    相关资源
    最近更新 更多