Flask sqlalchemy 无法创建表

我是python的新手。我正在尝试创建表并练习如何使用 Flask-SQLAlchemy 来创建声明性模型。当我运行时db.create_all(),出现以下错误。我不确定哪个部分是错误的。希望有经验的朋友帮帮我。

sqlalchemy.exc.ArgumentError: Mapper Mapper|TeacherUser|teacher_user could not assemble any primary key columns for mapped table 'teacher_user'
  • user -> search_condition 是一对一的

  • user <-> Teacher 是多对多的,teacherUser 是这两个表之间的关系表。

  • 用户 -> 类是多对一的

  • 用户 -> 书是一对多的

这是我的模型架构

from flaskr import db

from sqlalchemy import text

from datetime import datetime

from sqlalchemy.dialects.mysql import ENUM, JSON



class User(db.Model):

    __tablename__ = 'user'

    user_id = db.Column(db.Integer, primary_key=True)

    username = db.Column(db.String(50), unique=True, nullable=False)

    search_condition = db.relationship('SearchCondition', uselist=False, backref='user')


    teachers = db.relationship('TeacherUser', backref=db.backref('users', lazy='joined'), lazy='dynamic')


    class_id = db.Column(db.Integer, db.ForeignKey('classes.id'))

    classes = db.relationship('Classes', backref='classes')


    books = db.relationship('Book',backref='book')


    def __init__(self, username, email):

        self.username = username

        self.email = email


    def __repr__(self):

        return '<Demo %r>' % self.username


    def save(self):

        db.session.add(self)

        db.session.commit()



class SearchCondition(db.Model):

    __tablename__ = 'search_condition'

    search_condition_id = db.Column(db.Integer, primary_key=True)

    user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'))

    condition = db.Column(JSON, server_default=text(r"{}"))



class TeacherUser(db.Model):

    __tablename__ = 'teacher_user'

    user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'))

    teacher_id = db.Column(db.Integer, db.ForeignKey('teacher.teacher_id'))



class Teacher(db.Model):

    __tablename__ = 'teacher'

    teacher_id = db.Column(db.Integer, primary_key=True)

    participants = db.relationship('TeacherUser', backref=db.backref('teachers', lazy='joined'), lazy='dynamic')



慕桂英3389331
浏览 426回答 1
1回答

狐的传说

向模型添加复合主键class&nbsp;TeacherUser(db.Model): &nbsp;&nbsp;&nbsp;&nbsp;__tablename__&nbsp;=&nbsp;'teacher_user' &nbsp;&nbsp;&nbsp;&nbsp;user_id&nbsp;=&nbsp;db.Column(db.Integer,&nbsp;db.ForeignKey('user.user_id'),&nbsp;primary_key=True) &nbsp;&nbsp;&nbsp;&nbsp;teacher_id&nbsp;=&nbsp;db.Column(db.Integer,&nbsp;db.ForeignKey('teacher.teacher_id'),&nbsp;primary_key=True)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python