Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SqlAlchemy Relationship and Marshmallow

I am trying to return JSON or even a complete string of a returned one to many sqlalchemy query. I am using Marshmallow at this point to try do it but it keeps returning incomplete data

I have two models defined as :

class UserModel(db.Model):
    __tablename__ = 'usermodel'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    password = db.Column(db.String(120))
    weekday = db.relationship('weekDay', cascade='all,delete-orphan', single_parent=True, backref=db.backref('usermodel', lazy='joined'))

class weekDay(db.Model):
    __tablename__ = 'weekday'
    id = db.Column(db.Integer, primary_key=True)
    #Defining the Foreign Key on the Child Table
    dayname = db.Column(db.String(15))
    usermodel_id = db.Column(db.Integer, db.ForeignKey('usermodel.id'))

I have defined two schemas

class WeekdaySchema(Schema):
    id = fields.Int(dump_only=True)
    dayname = fields.Str()

class UserSchema(Schema):
    id = fields.Int(dump_only=True)
    username = fields.Str()
    password = fields.Str()
    weekday = fields.Nested(WeekdaySchema)

and finally I run the command (I pass the name in userName variable)

 userlist = UserModel.query.filter_by(parentuser=userName).all()
 full_schema = UserSchema(many=True)
 result, errors = full_schema.dump(userlist)
 print (result)

I print the result to see before I attempt to Jsonify it: My weekday object is completely empty

'weekday': {}

Doesn anyone know how I can do this correctly

like image 642
Zee18 Avatar asked Jun 13 '16 19:06

Zee18


1 Answers

It's a one-to-many relationship and you must indicate it on UserSchema, like that

class UserSchema(Schema):
    id = fields.Int(dump_only=True)
    username = fields.Str()
    password = fields.Str()
    weekday = fields.Nested(WeekdaySchema, many=True)

read more on documentation

like image 145
Filipe Amaral Avatar answered Oct 13 '22 08:10

Filipe Amaral