consider following code defining classes:
from sqlalchemy.ext.declarative import declarative_base sqlalchemy import column, integer, float, string, datetime sqlalchemy import foreignkey, uniqueconstraint 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) and following code using classes:
from sqlalchemy import create_engine 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') first of all, want know if defining c1 right way (using teacher argument.)
second of all, know if can teacher of student doing:
s1.class.teacher but there anyway ( , normal) create teacher attribute directly on student class? tried adding:
teacher = class.teacher in class definition, threw:
attributeerror: 'relationshipproperty' object has no attribute 'teacher' obviously, it's not big of deal, want know correct way (if there one, or there not one) i'm trying learn sqlalchemy better.
so discovered answer second question... do
@property def teacher(self): return self.class.teacher this generic python classes (new-style think.)
now
s1.class.teacher returns teacher object.
edit: since no 1 else has answered question, , code works how think should, i'm going coded correct way (in reference question 1.)
Comments
Post a Comment