I have a simple Flask-SQLAlchemy model, which I'm writing a REST API for:
class Report(db.Model, CRUDMixin):
report_id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.user_id'), index=True)
report_hash = Column(Unicode, index=True, unique=True)
created_at = Column(DateTime, nullable=False, default=dt.datetime.utcnow)
uploaded_at = Column(DateTime, nullable=False, default=dt.datetime.utcnow)
Then I have the corresponding Marshmallow-SQLAlchemy schema:
class ReportSchema(ModelSchema):
class Meta:
model = Report
However, in my rest API, I need to be able to dump and load slightly different variants of this model:
- When dumping all the reports (e.g.
GET /reports
), I want to dump all the above fields. - When dumping a single report (e.g.
GET /reports/1
), I want to dump all this data, and also all associated relations, such as the associatedSample
objects from thesample
table (one report has many Samples) - When creating a new report (e.g.
POST /reports
), I want the user to provide all the report fields exceptreport_id
(which will be generated),report_hash
anduploaded_at
(which will be calculated on the spot), and also I want them to include all the associatedSample
objects in their upload.
How can I reasonably maintain 3 (or more) versions of this schema? Should I:
- Have 3 separate
ModelSchema
subclasses? e.g.AggregateReportSchema
,SingleReportSchema
, andUploadReportSchema
? - Have one mega-
ModelSchema
that includes all fields I could ever want in this schema, and then I subtract fields from it on the fly using theexclude
argument in the constructor? e.g.ReportSchema(exclude=[])
? - Or should I use inheritance and define a
class ReportBaseSchema(ModelSchema)
, and the other schemas subclass this to add additional fields (e.g.class UploadReportSchema(ReportBaseSchema)
)? - Something else?