Search code examples
flasksqlalchemymarshmallow

ma.Nested probably does not work sqlalchemy and marshmallow


I have one to many relationships between tables in a database and I want to get the data using an API. I think that ma.Nested does not work because I don't get all the fields can anyone help me?

I get only this : [ { "IsRef": false, "commands": [ "299d7f0b-721c-484b-9448-072716a5fd70", "382c5d9f-99a1-4aa2-ac30-96084e202fad", "299d7f0b-721c-484b-9448-072716a5fd75", "382c5d9f-99a1-4aa2-ac30-96084e202fak" ], "filename": "uiyg", "version": 8 } ]

this is the database model :

class File(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.String(255), unique=True)
    version = db.Column(db.Integer, unique=True)
    IsRef = db.Column(db.Boolean)
    commands = db.relationship('Command', backref='log', lazy='joined')

    def __init__(self, filename, version, IsRef):
        self.filename = filename
        self.version = version
        self.IsRef = IsRef


class Command(db.Model):
    id_command = db.Column(db.String(255), primary_key=True, autoincrement=False)
    name = db.Column(db.String(255))
    log_id = db.Column(db.Integer, db.ForeignKey('file.id'))
    status = db.Column(db.Boolean)
    events = db.relationship('Event', backref='com', lazy='joined')

    def __init__(self, id_command, name, log_id, status):
        self.id_command = id_command
        self.name = name
        self.log = log_id
        self.status = status


class Event(db.Model):
    id_event = db.Column(db.Integer, primary_key=True)
    event_name = db.Column(db.String(255))
    seq_number = db.Column(db.Integer)
    com_id = db.Column(db.Integer, db.ForeignKey('command.id_command'))

    def __init__(self, event_name, seq_number, com_id):
        self.event_name = event_name
        self.seq_number = seq_number
        self.com = com_id

this is the schema :


class EventSchema(ma.ModelSchema):
    class Meta:
        model = Event
        fields = ('event_name', 'seq_number')


class CommandSchema(ma.ModelSchema):
    class Meta:
        model = Command
        events = ma.Nested(EventSchema)
        fields = ('id_command', 'name', 'status', 'events')



class LogSchema(ma.ModelSchema):
    class Meta:
        model = File
        commands = ma.Nested(CommandSchema)
        fields = ('filename', 'version', 'IsRef', 'commands')



Log_schema = LogSchema(many=True)

this is the API :

@app.route("/getall/<version>", methods=["GET"])
def get_all(version):
    alle = File.query.filter_by(version=version)
    return Log_schema.jsonify(alle)

Solution

  • this question is solved. I've changed 'lazy ='joined'' to 'lazy='dynamic'' and I've put ma.Nested out of the Meta class