Karthik
Karthik

Reputation: 2581

Flask-SQLAlchemy-Marshmallow Nesting

I'm trying to serialize data from a One-To-Many relationship models using Marshmallow in Flask. I read the Marshmallow and SQLAlchemy docs, but couldn't make it work. Could anyone help me.

Models:

class Category(db.Model):
    __tablename__ = 'category_mn'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(45))
    status = db.Column(db.Integer, server_default=db.FetchedValue())
    items = db.relationship('Items', backref='category', lazy='dynamic')
    timestamp = db.Column(db.DateTime, server_default=db.FetchedValue())


class Items(db.Model):
    __tablename__ = 'items_mn'

    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(100))
    category_id = db.Column(db.Integer, db.ForeignKey('category_mn.id'))
    timestamp = db.Column(db.DateTime, server_default=db.FetchedValue())

Schemas:

class CatSchema(ma.ModelSchema):
    class Meta:
        model = Category
        fields = ('id', 'name', 'status')


class ItemSchema(ma.ModelSchema):

    class Meta:
        model = Items
        fields = ('id', 'name')
    category = ma.Nested(CatSchema, many=True)

I'm looking for an output like this:

[{'id':1, 'name':'Test', 'category':{'id':1, 'name':'Test Cat'}}]

Upvotes: 8

Views: 8993

Answers (1)

Luis Orduz
Luis Orduz

Reputation: 2887

You're referencing models that don't exist in your schemas.

Besides that, category in Items is not iterable (it's the "one" side of the "one-to-many" relationship), so the many=True parameter throws an error.

And category should appear in the fields attribute of the Meta class for ItemSchema so it actually appears in the serialization.

It should be like this:

class CatSchema(ma.ModelSchema):
  class Meta:
    model = Category
    fields = ('id', 'name', 'status')


class ItemSchema(ma.ModelSchema):

  class Meta:
    model = Items
    fields = ('id', 'name', 'category')
  category = ma.Nested(CatSchema)

Of course, you could simply not include the fields attribute in the meta classes at all, since model is already taking care of mapping the models.

Upvotes: 11

Related Questions