我創建了一個表users
在shell中的MySQL聲明:瓶/ SQLAlchemy的 - 錯誤創建模型與關係
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(40) NOT NULL,
`email` varchar(120) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB;
和一張桌子posts
有這樣的說法:
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(140) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_user_id` (`user_id`),
CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB;
我想在我的Flask應用程序中使用這些表。我創建了一個連接posts
到users
的外鍵。它應該與擁有許多帖子的用戶成爲一對多的關係。
在我的Python代碼中,我有以下型號:
class Users(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(40), unique=True)
email = db.Column(db.String(120), unique=True)
posts = db.relationship('Posts', backref='user', lazy='dynamic')
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User {}>'.format(self.username)
class Posts(db.Model):
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.String(140))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
當我嘗試運行我的瓶的應用程序不過,我不斷收到錯誤:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Original exception was: Could not determine join condition between parent/child tables on relationship Users.posts - there are no foreign keys linking these tables.
但我創建的外鍵連接mysql語句中的posts
到users
。當我拿出posts = db.relationship('Posts', backref='user', lazy='dynamic')
這行時,一切正常,所以問題在於那段代碼。我的設置有哪些是錯誤的?
使用'create_all()'做了詭計! – rcplusplus
真棒,只是驗證你的關係工作,因爲他們應該。表可以創建'奇怪'的關係定義沒有錯誤,但結束不能按預期工作。 –