sqlalchemy - 无法使用单独的类映射父表和子表

时间:2018-04-17 18:52:37

标签: python flask sqlalchemy

注意:我知道这是一个冗长的帖子,我已经包含了太多的代码,但我不知道什么是重要的,什么不是,因为我对SQLAlchemy来说还是个新手。非常抱歉给您带来不便

我试图在两个表之间映射多对多关系,但同时我还必须添加另一个可以在开头保存空值的字段。

到目前为止,我尝试过以下代码:

this example from github

this already provided solution

并且最终没有任何工作。这是我的代码,请帮我找出我的错误。如果可能的话,添加一个如何工作的描述,因为我不熟悉Python和SQLAlchemy

Test.py:

from app.Blueprints import db

class Test(db.Model):
    __tablename__ = "test"
    id = db.Column("id", db.Integer, primary_key=True)
    name = db.Column("name", db.Unicode)

    def __init__(self, name):
        self.name = name

Student.py:

from app.Blueprints import db, connection

class Student(db.Model):
    __tablename__ = "student_master"
    id = db.Column("id", db.Integer, primary_key = True)
    fname = db.Column("first_name", db.Unicode)
    lname = db.Column("last_name", db.Unicode)
    email = db.Column("email", db.Unicode, unique = True)
    passwd = db.Column("passwd", db.Unicode)


    def __init__(self, fname, lname, email):
        passwd = fname+" "+lname
        picture = "default.jpg"
        state = 1
        reg_date = strftime("%Y-%m-%d")
        self.fname = fname
        self.lname = lname
        self.email = email
        self.passwd = passwd

Test_Student.py [映射测试和学生的模型,以及额外的成绩字段]:

from app.models.Test import Test
from app.models.Student import Student
from app.Blueprints import db



class Test_Students(db.Model):
    __tablename__ = "test_student"
    test = db.Column("test_id", db.Integer, db.ForeignKey('test.id'), primary_key = True)
    student = db.Column("student_id", db.Integer, db.ForeignKey("student.id"), primary_key = True)
    grade = db.Column("grade", db.Float, nullable = True)

    tests = db.relationship(Test, backref="students")
    students = db.relationship(Student, backref="students")

这就是我创建新测试的方式:

if request.method == "POST" :
        from app.Blueprints import db
        from app.models.Test import Test
        from app.models.Test_students import Test_Students
        from app.models.Student import Student
        #register test
        newTest = Test(request.form.get("name"), request.form.get("date"), request.form.get("type"))
        db.session.add(newTest)
        db.session.commit()
        #map test with students
        StudentList = request.form.getlist("StudentList[]")
        for student in StudentList:
            stud = Student.query.get(student)
            newTest.students.append(stud)

当我尝试执行时,我收到以下错误:

  

sqlalchemy.exc.NoForeignKeysError:无法确定关系Test_Students.students上的父/子表之间的连接条件 - 没有链接这些表的外键。确保引用列与ForeignKey或ForeignKeyConstraint相关联,或指定“primaryjoin”表达式。

0 个答案:

没有答案