sqlalchemy定义一对多表时出现的问题:
# 定义数据库的表
class Author(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(70), unique=True)
phone = db.Column(db.String(20))
articles = db.relationship('article')
class Article(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(50), unique=True)
body = db.Column(db.Text)
author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
上面的代码是定义的表,在shell中运行时:
aaa = Author(name='aaa')
报出如下的错误
sqlalchemy.exc.ArgumentError: relationship 'articles' expects a class or a mapper argument (received: <class 'sqlalchemy.sql.schema.Table'>)
原因:定义关系的时候
articles = db.relationship('article')
解决方法:article需要大写,与表定义匹配。