0

考虑以下定义一些类的代码:

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。

4

1 回答 1

0

所以我发现了我的第二个问题的答案......就做

@property
def Teacher(self):
    return self.Class.Teacher

这对于 python 类是通用的(我认为只有新样式。)

现在

s1.Class.Teacher

返回教师对象。

编辑:由于没有其他人回答我的问题,并且我的所有代码都按照我认为的方式工作,所以我要说我以正确的方式编码它(参考问题 1。)

于 2013-05-06T23:29:00.790 回答