How to specify an association relation using declarative base
I have been trying to create an association relation between two tables, intake
and module
. Each intake has a one-to-many relationship with the modules.
However there is a coursework assigned to each module, and each coursework has a duedate
which is uni开发者_如何学JAVAque to each intake.
I tried this but it didnt work:
intake_modules_table = Table('tg_intakemodules',metadata,
Column('intake_id',Integer,ForeignKey('tg_intake.intake_id',
onupdate="CASCADE",ondelete="CASCADE")),
Column('module_id',Integer,ForeignKey('tg_module.module_id',
onupdate ="CASCADE",ondelete="CASCADE")),
Column('dueddate', Unicode(16))
)
class Intake(DeclarativeBase):
__tablename__ = 'tg_intake'
#{ Columns
intake_id = Column(Integer, autoincrement=True, primary_key=True)
code = Column(Unicode(16))
commencement = Column(DateTime)
completion = Column(DateTime)
#{ Special methods
def __repr__(self):
return '"%s"' %self.code
def __unicode__(self):
return self.code
#}
class Module(DeclarativeBase):
__tablename__ ='tg_module'
#{ Columns
module_id = Column(Integer, autoincrement=True, primary_key=True)
code = Column(Unicode(16))
title = Column(Unicode(30))
#{ relations
intakes = relation('Intake',
secondary=intake_modules_table, backref='modules')
#{ Special methods
def __repr__(self):
return '"%s"'%self.title
def __unicode__(self):
return '"%s"'%self.title
#}
When I do this the column duedate
specified in the intake_module_table
is not created.
Please some help will be appreciated here.
thanks in advance
Actually column duedate
is created, but you don't get it as some model attribute when querying your models. I you need to define intermediate model for intake_modules_table
table and setup relation to it instead of Intake
. Sure, the access to columns of relation will be a bit longer (module.infakes[0].duedate
, module.infakes[0].infake.code
). Also you can setup association proxy to access list of Infake
objects the same way you do now.
精彩评论