Freddie Witherden
Freddie Witherden

Reputation: 2426

SQLAlchemy One-to-One relationships

I have a File class:

class File(DeclarativeBase):
    __tablename__ = 'files'

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

which I use for storing attachments in my application. I also have a Note class:

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")

where fid can be NULL if the user has not attached a file. In addition to Note other classes also make use of an fid column for handling attachments.

However, I am wondering how I can make the creation of a note more elegant. Specifically, I would like to be able to do something like Note(note=note_text,file=File(...)) and have SQLAlchemy take care of inserting a new entry into files. Similarly, for an existing Note, I would like to be able to do n.file = File(...) or n.file = None and have everything just work with there being no orphaned entries in files.

Upvotes: 1

Views: 566

Answers (1)

Xion
Xion

Reputation: 22770

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).

Upvotes: 1

Related Questions