考虑以下代码定义一些类:
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是否正确(使用Teacher参数)。
其次,我知道我是否可以通过以下方式获得学生的老师:
s1.Class.Teacher
但是直接在Student类上创建一个Teacher属性是否正常(并且是正常的)?我尝试添加:
Teacher = Class.Teacher
在类定义中,但是扔了:
AttributeError: 'RelationshipProperty' object has no attribute 'Teacher'
显然,这并不是什么大不了的事,但我想知道正确的方法(如果有的话,或者没有一个),因为我正在努力学习sqlalchemy。
答案 0 :(得分:0)
所以我发现了第二个问题的答案......就这样做
@property
def Teacher(self):
return self.Class.Teacher
这对于python类是通用的(我认为只有新风格。)
现在
s1.Class.Teacher
返回Teacher对象。
编辑:由于没有其他人回答我的问题,并且我的所有代码都按照我的想法运作,我会说我用正确的方式对其进行编码(参考问题1)。