python - How do you use the `secondary` kwarg to fit this situation in SqlAlchemy? -


i have situation user can belong many courses, , course can contain many users. have modeled in sqlalchemy so:

class user(base):     __tablename__ = 'users'      id = column(integer, primary_key=true)   class course(base):     __tablename__ = 'courses'      id = column(integer, primary_key=true)     archived = column(datetime)   class coursejoin(base):     __tablename__ = 'course_joins'      id = column(integer, primary_key=true)      # foreign keys     user_id = column(integer, foreignkey('users.id'))     course_id = column(integer, foreignkey('courses.id')) 

in system, have ability "archive" course. marked datetime field on course model. give user model relationship called course_joins contains coursejoins respective course hasn't been archived. i'm trying use secondary kwarg accomplish so:

class user(base):     __tablename__ = 'users'      id = column(integer, primary_key=true)      course_joins = relationship('coursejoin',                                 secondary='join(course, coursejoin.course_id == course.id)',                                 primaryjoin='and_(coursejoin.user_id == user.id,'                                                  'course.archived == none)',                                 order_by='coursejoin.created') 

however i'm getting error:

invalidrequesterror: 1 or more mappers failed initialize - can't proceed initialization of other mappers.  original exception was: expression expected 

i believe exact usecase secondary kwarg of relationship(), i'm not sure what's going on.

if have many-to-many relationship (plus created) column, think right way define relationship is:

courses = relationship(     'course',     secondary='course_joins',     primaryjoin='users.c.id == course_joins.c.user_id',     secondaryjoin='and_(courses.c.id == course_joins.c.course_id, courses.c.archived == none)',     order_by='course_joins.c.created',     viewonly=true, ) 

and use like:

u1 = user(courses=[course()]) session.add(u1) u2 = user(courses=[course(archived=datetime.date(2013, 1, 1))]) session.add(u2) 

otherwise, drop secondary , add other condition primaryjoin:

courses = relationship(     'coursejoin',     primaryjoin=\     'and_(users.c.id == course_joins.c.user_id, '     'courses.c.id == course_joins.c.course_id, '     'courses.c.archived == none)',     order_by='course_joins.c.created', ) 

Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -