1

我有一File堂课:

class File(DeclarativeBase):
    __tablename__ = 'files'

    id        = Column(Integer, primary_key=True)
    name      = Column(String)
    mime_type = Column(String)
    data      = Column(LargeBinary)

我用于在我的应用程序中存储附件。我也有一Note堂课:

class Note(DeclarativeBase):
    __tablename__ = 'notes'

    id   = Column(Integer, primary_key=True)
    note = Column(String)
    fid  = Column(Integer, ForeignKey('files.id'))

    file = relationship('File', uselist=False, cascade="all, delete-orphan")

如果用户没有附加文件,fid可以在哪里。NULL除了Note其他类之外,还使用fid列来处理附件。

但是,我想知道如何使笔记的创建更加优雅。具体来说,我希望能够做类似的事情Note(note=note_text,file=File(...))并让 SQLAlchemy 负责将新条目插入files. 同样,Note对于现有的.n.file = File(...)n.file = Nonefiles

4

1 回答 1

1

SQLAlchemy will persist all your Note and File objects in database session, assigning foreign keys appropriately during Session.flush. There isn't anything else you need to do besides defining the relationships correctly (which, as I can see, you have already done).

于 2012-07-16T08:41:30.787 回答