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.
SQLAlchemy will persist all your
NoteandFileobjects in database session, assigning foreign keys appropriately duringSession.flush. There isn’t anything else you need to do besides defining therelationships correctly (which, as I can see, you have already done).