marshmallow-sqlalchemy
marshmallow-sqlalchemy copied to clipboard
Idea: fields.Relationship
I often use fields.Nested to handle relationships (fields.Related doesn't do what I need). This idea for fields.Relationships creates a fields.Nested, where the schema is based on the parent schema, and the sqlalchemy class for the relation. It does "many" automatically, and also excludes the foreign key to the parent (which is redundant). Example usage:
class OrderSchema(ModelSchema):
class Meta:
model = db.Order
sqla_session = db.session
items = Relationship()
This is the code I'm using:
class Relationship(fields.Nested):
def __init__(self, **kwargs):
super(Relationship, self).__init__(None, **kwargs)
@property
def schema(self):
if not hasattr(self, '_schema'):
property = getattr(self.root.Meta.model, self.attribute or self.name).property
self.many = property.uselist
class InnerSchema(ModelSchema):
class Meta(self.root.Meta):
model = property.mapper.class_
exclude = [c.name for c in property.remote_side]
self._schema = InnerSchema()
return self._schema
What I would really like to do - and I'm not sure how at the minute - is have this span multiple levels of relationship.