Question: best way on how to organize CRUD schema objects with marshmallow
See original GitHub issueHi, one question on what is the best practice to organize marshmallow schema objects for CRUD methods. Say, I have a simple class in SqlAlchemy:
class Order(Base):
__tablename__ = 'Orders'
id = Column(Integer, primary_key=True)
name = Column(String)
quantity = Column(Integer)
placed_at = Column(DateTime)
Now, when creating new Order, I need schema that has name field only (and eventually placed_at automatically set to datetime.utcnow()
). When updating, my endpoint for example should allow to change only name and quantity fields. On reading (and delete) however I want all fields: id, name, quantity and placed_at to be serialized (dumped).
What is the best/recommended way to do this: shall I crate one base class, containing the smallest set of attributes and then extend it (subclass it) and add additional fields? Or, shall I simply create different classes with no common class. I prefer using the base class approach whenever possible, but I am not sure will this complicate managing of dump_only and exclude_fields in sub-classes and make code hard to maintain?
Thank you in advance
Issue Analytics
- State:
- Created 5 years ago
- Comments:6 (3 by maintainers)
Top GitHub Comments
You can filter schema attributes when loading and dumping using the
only
,exclude
, andpartial
arguments.Yes, I am thinking the same, but trouble is that service code should be used both in endpoints and console application doing some administrative stuff directly (without usage of REST), so it seems I will have to keep validation inside service itself in order not to duplicate it. Second option is to use schema instance and perform validation inside service, but somehow this look more as the job for some ‘parameter’ class that will be instantiated within the service and raise an exception in __init__ automatically, or via separate validate() method that should be called upon creation of ‘param’ object