On Thu, 2012-02-23 at 14:49 -0500, Adam Tauno Williams wrote:
> I have a database where multiple objects use the same sequence to
> generate primary keys -
> class ProjectInfo(Base, KVC):
>     __tablename__       = 'project_info'
>     object_id           = Column("project_info_id", Integer,
>                                  Sequence('key_generator'),
>                                  primary_key=True)
>     project_id          = Column("project_id",
> ForeignKey('project.project_id'), )
> ..
> class Project(Base, KVC):
>     """ An OpenGroupware Project object """
>     __tablename__       = 'project'
>     object_id           = Column("project_id",
>                                 Sequence('key_generator'),
>                                 ForeignKey('project_info.project_id'),
> ..
> Project.info = relation("ProjectInfo", uselist=False,
> back_populates="project",
> primaryjoin=(ProjectInfo.project_id==Project.object_id))
> ProjectInfo.project = relation("Project", uselist=False, backref="info",
> primaryjoin=(ProjectInfo.project_id==Project.object_id)
> This works fine.  But if I create a Project object I can't relate it to
> a ProjectInfo object within the same transaction without calling flush()
> first.  Is there some way to encourage SQLalchemy to allocate a value
> from the sequence when the object is created
> Basically a ProjectInfo should be created for every Project that is
> created; this relationship is one-to-one.

I solved my problem using an association proxy and the info entry is
maintained / created just as an attribute of the Project class.  This
seems to work very well.

class Project(Base):
    ...
    project = relation("Project", 
                       uselist=False, 
                       backref=backref("project", cascade="all,
delete-orphan"),
primaryjoin=('ProjectInfo.project_id==Project.object_id'))       

class ProjectInfo(Base):
    ...
    info = relation("ProjectInfo", 
                    uselist=False,
                    backref=backref('project_info'),

primaryjoin=('ProjectInfo.project_id==Project.object_id'))    
                    
    comment = association_proxy('info', 'comment')

Attachment: signature.asc
Description: This is a digitally signed message part

Reply via email to