考虑以下定义一些类的代码:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, Float, String, DateTime
from sqlalchemy import ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship, backref
class Base(object):
id = Column(Integer, primary_key=True)
Base = declarative_base(cls=Base)
class Teacher(Base):
__tablename__ = 'teacher'
email = Column(String, unique=True)
name = Column(String, nullable=False)
password = Column(String)
base_score = Column(Float)
time_zone = Column(String)
def __repr__(self):
return '<Teacher({0})>'.format(self.email)
class Class(Base):
__tablename__ = 'class'
teacher_id = Column(Integer, ForeignKey('teacher.id', ondelete="CASCADE"), nullable=False, index=True)
Teacher = relationship("Teacher", backref=backref('classes', order_by='Class.id'))
name = Column(String, index=True)
__table_args__ = (UniqueConstraint('teacher_id','name'),)
def __repr__(self):
return '<Class({0})>'.format(self.name)
class Student(Base):
__tablename__ = 'student'
class_id = Column(Integer, ForeignKey('class.id', ondelete="CASCADE"), nullable=False, index=True)
Class = relationship("Class", backref=backref('students', order_by='Student.id'))
name = Column(String, index=True)
__table_args__ = (UniqueConstraint('class_id','name'),)
def __repr__(self):
return '<Student({0})>'.format(self.name)
以及使用类的以下代码:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('sqlite:///:memory:', echo=True)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
t = Teacher(email='test@example.com',name='Cool Guy',base_score=100,time_zone='America/Chicago')
c1 = Class(Teacher=t,name='Mathematics')
s1 = Student(Class=c1,name='Bob Roberts')
首先,我想知道这样定义 c1 是否正确(使用教师参数。)
其次,我知道我是否可以通过以下方式获得学生的老师:
s1.Class.Teacher
但是无论如何(这是否正常)直接在 Student 类上创建一个 Teacher 属性?我尝试添加:
Teacher = Class.Teacher
在类定义中,但这抛出了:
AttributeError: 'RelationshipProperty' object has no attribute 'Teacher'
显然,这没什么大不了的,但是我想知道正确的方法(如果有,或者没有),因为我正在尝试更好地学习 sqlalchemy。