Python3 "TypeError: not all arguments converted during string formatting"

标签 python

我正在使用 Flask SQLAlchemy 模型为我的应用程序创建数据库,并且我正在尝试使用 models.Posts.query.all() 查询数据库 这是我的模型:

class Posts(db.Model):
    post_id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(500), index=True)
    date = db.Column(db.Date)
    image = db.Column(db.String(500))
    post_body = db.column(db.String(10000),index=True)
    authors = db.relationship('Users', backref='authors', lazy='dynamic')

def __repr__(self):
    return '' % (self.post_id, self.title, self.date, self.image)

这是我收到的错误消息:

>>> models.Posts.query.all()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/lisa-jd/Blog_platform/app/models.py", line 30, in __repr__
    image = db.Column(db.String(50))
TypeError: not all arguments converted during string formatting

任何帮助将不胜感激。

最佳答案

错误消息有点神秘,但给出了提示:

File "/Users/lisa-jd/Blog_platform/app/models.py", line 30, in __repr__

你的__repr__函数:

def __repr__(self):
    return '' % (self.post_id, self.title, self.date, self.image)

如果被调用,则会触发臭名昭著的消息,如这个简单的示例所示:

>>> "" % 10
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
TypeError: not all arguments converted during string formatting

您正在将 3 个参数传递给一个空格式字符串。也许你的意思是这样的:

def __repr__(self):
    return '%s: %s %s' % (self.post_id, self.title, self.date, self.image)

或使用str.format

def __repr__(self):
    return '{}: {} {}'.format(self.post_id, self.title, self.date, self.image)

关于Python3 "TypeError: not all arguments converted during string formatting",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47606702/

相关文章:

python - 在一个查询中从三个表中选择给出相乘的结果

python,多次运行 def()

python - 在python中使用ffmpeg切割mp3 - 编解码器复制错误

python - 不正确的 : usage of hyperopt with tensorflow

python - 你如何定期清除 Google Colab 的输出

javascript - Python bokeh CustomJS 回调更新 DataTable 小部件

python - 如何通过Python将时间戳值插入MongoDB上的ISODate类型?

python - 细数汉诺塔的 Action

python - 线程在 Python 中随机停止

python - 如何从 whl 文件安装 python 包