如何使用声明性基础指定关联关系

时间:2009-12-22 11:27:16

标签: sqlalchemy associations relation

我一直在尝试在两个表intakemodule之间创建关联关系。每个入口与模块具有一对多的关系。 但是,每个模块都有一个课程作业,每个课程都有一个duedate,每个课程都是独一无二的。

我尝试了这个,但它没有用:

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
    #}

执行此操作时,不会创建duedate中指定的列intake_module_table。 请在这里获得一些帮助。

提前致谢

1 个答案:

答案 0 :(得分:0)

实际上已创建列duedate ,但在查询模型时,您不会将其作为某些模型属性。我需要为intake_modules_table表定义中间模型并设置与它的关系,而不是Intake。当然,对关系列的访问会稍长一些(module.infakes[0].duedatemodule.infakes[0].infake.code)。您也可以设置关联代理来访问Infake对象列表,就像现在一样。