Serialize in flask-marshmallow with relationship

Asked

Viewed 146 times

0

I’m using the flask-marshmallow to make the serialize in my project. Along with it I am using flask-sqlalchemy for mapping my tables.

Follows the structure:

models/Area.py:

config.database import db


class Area(db.Model):
    __tablename__ = 'AREA'
    
    id = db.Column('AREA_ID', db.Integer, primary_key=True)
    name = db.Column('AREA_NOME', db.String, nullable=False)
    deleted = db.Column('AREA_DELETADO', db.Boolean, default=False)
    project_id = db.Column('PROJETO_ID', db.Integer, db.ForeignKey('PROJETO.PRJ_ID'), nullable=False)

    project = db.relationship('Project', backref='project', uselist=False)

models/Project.py:

from config.database import db


class Project(db.Model):
    __tablename__ = 'PROJETO'

    id = db.Column('PROJETO_ID', db.Integer, primary_key=True)
    desc = db.Column('PROJETO_DESCRICAO', db.String, nullable=False)

schemas/Areaschema.py:

from config.marshmallow import ma
from ..models.Area import Area


class AreaSchema(ma.SQLAlchemyAutoSchema):
    class Meta:
        model = Area
        include_fk = True

Service to serialize:

def get(id):
    area = Area.query.filter_by(
        deleted=False,
        id=id
    ).first()

    if area is None:
        raise NotFound('Area not found')

    area_schema = AreaSchema()
    output = area_schema.dump(area)
    return jsonify({'data': output})

Output:

{
    "data": {
        "deleted": false,
        "id": 10,
        "name": "Nome da Area",
        "project_id": 1
    }
}

I need the Project data to appear in the output as well, I did according to the documentation and it is not working. What would be the problem?

1 answer

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.