这是一个基本todo应用的模型,用户可以在其中创建包含任务的任务列表:
from flask.ext.sqlalchemy import SQLAlchemy
from allot import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
tasklists = db.relationship('Tasklist', backref='user', lazy='dynamic')
tasks = db.relationship('Task', backref='user', lazy='dynamic')
def __init__(self, username, email):
self.username = username
class Tasklist(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
user_id = db.Column(db.Integer, db.ForeignKey('User.id'))
tasks = db.relationship('Task', backref='tasklist', lazy='dynamic')
def __init__(self, title, description, user_id):
self.title = title
self.user_id = user_id
class Task(db.Model):
id = db.Column(db.Integer, primary_key=True)
title= db.Column(db.String)
user_id = db.Column(db.Integer, db.ForeignKey('User.id'))
tasklist_id = db.Column(db.Integer, db.ForeignKey('Tasklist.id'))
def __init__ (self, title, status, user_id):
self.title = title
self.user_id = user_id
self.tasklist_id = tasklist_id
它会生成此错误:
ArgumentError:无法确定父/子之间的连接条件 关系User.tasklists上的表。指定'主要连接' 表达。如果' secondary'存在,' secondaryjoin'需要作为 好。
在关系中添加primaryjoin
个参数,如下所示:
tasklists = db.relationship('Tasklist', backref='user', primaryjoin='user.id==Tasklist.user_id', lazy='dynamic')
...返回:
InvalidRequestError:一个或多个地图制作者无法初始化 - 无法解决 继续初始化其他映射器。
该模型有什么问题?
我在[关系] [1] doc和SO上搜索了一个解释,但没有用。
答案 0 :(得分:0)
一种可能性是,当您使用大写字母" User"当您确实需要使用小写的 tablename 引用时。试试这个:
from flask.ext.sqlalchemy import SQLAlchemy
from allot import db
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
tasklists = db.relationship('Tasklist', backref='user', lazy='dynamic')
tasks = db.relationship('Task', backref='user', lazy='joined'))
def __init__(self, username, email):
self.username = username
class Tasklist(db.Model):
__tablename__ = 'tasklist'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
tasks = db.relationship('Task', backref='tasklist', lazy='dynamic')
def __init__(self, title, description, user_id):
self.title = title
self.user_id = user_id
class Task(db.Model):
__tablename__ = 'task'
id = db.Column(db.Integer, primary_key=True)
title= db.Column(db.String)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
tasklist_id = db.Column(db.Integer, db.ForeignKey('tasklist.id'))
def __init__ (self, title, status, user_id):
self.title = title
self.user_id = user_id
self.tasklist_id = tasklist_id