marshmallow-code / marshmallow-sqlalchemy

SQLAlchemy integration with marshmallow
https://marshmallow-sqlalchemy.readthedocs.io
MIT License
560 stars 95 forks source link

Allow to serialize the complete parent object in a child object #327

Open serlesen opened 4 years ago

serlesen commented 4 years ago

Having those two objects:

class Product(Model):
    __tablename__: product_table_name

   id = Column(Integer, primary_key=True)
   name = Column(String)

class BasketItem(Model):
    __tablename__: basket_item_table_name
    id = Column(Integer, primary_key=True)
    product_id = Column(
        Integer, ForeignKey(f"{product_table_name}.id"), nullable=False
    )
    product = relationship("Product", foreign_keys="BasketItem.product_id")

I want, when returning the basket item, have the product serialized inside, not only the ID. Here are the ModelSchema i've used:

class ProductBasketItemSchema(ModelSchema):
    class Meta:
        model = Product
        fields = ("id", "name",)

class BasketItemSchema(ModelSchema):
    class Meta:
        model = BasketItem
        include_relationships = True
        fields = ("id", "product",)
    product: Nested(ProductBasketItemSchema, many=False)

This will serialize something like: [{'id': 1, 'product': 123}] Add some flag in the Meta declaration to allow serializing the following: [{'id': 1, 'product': {'id': 123, 'name': 'first'}}]

serlesen commented 4 years ago

This can be done with a more complex manual mapping as described in the following issue: https://stackoverflow.com/questions/62515255/how-to-serialize-a-nested-object-with-the-many-to-one-relationship-in-one-side/62539383#62539383