0

I am new to flask and try to wtite a user role association service. I defined the three database models in a following way:

from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class user(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  ... some other fields
  roles = db.relationship("Role", secondary='user_roles')

class Role(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  role_name = db.Column(db.String(80), unique=True, nullable=False)

class UserRoles(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  user_id = db.Column(db.Integer, db.ForeignKey("user.id", ondelete='CASCADE'), nullable=False)
  role_id = db.Column(db.Integer, db.ForeignKey("role.id", ondelete='CASCADE'), nullable=False)

The respective schemas are:

from flask_marshmallow import Marshmallow

ma = Marshmallow()

class UserSchema(ma.ModelSchema):
    id = ma.Int(dump_only=True)
    roles = ma.Nested(RoleSchema(only=("role_name",)))

    class Meta:
        model = User
        sqla_session = db.session

class RoleSchema(ma.ModelSchema):

    id = ma.Int(dump_only=True)

    class Meta:
        model = Role
        sqla_session = db.session

class UserRoleSchema(ma.ModelSchema):
    id = ma.Int(dump_only=True)

    class Meta:
        model = UserRoles
        sqla_session = db.session
        include_fk = True

When I tried to execute I got the following marshmallow validation error:

{'roles': {'_schema': ['Invalid input type.']}}

I understood the message but due to a lack of knowledge, I could not find the solution. Any help is highly appreciated.

  • A `User` can have many `Role`. `UserSchema.roles = ma.Nested(RoleSchema(...))` configures your schema for a user to only have a single Role, that is not a list of Roles. So maybe you want `ma.List(ma.Nested(RoleSchema(...)))`. Here is relevant marshmallow docs: https://marshmallow.readthedocs.io/en/stable/nesting.html – SuperShoot Mar 15 '20 at 11:41
  • @SuperShoot I am using flask marshmallow and i found error when I use list because flask marshmallow has nothing related with list operation. – Khan Hafizur Rahman Mar 15 '20 at 18:13
  • You need to import it from `marshmallow` not `flask-marshmallow`: `from marshmallow.fields import List`. – SuperShoot Mar 16 '20 at 00:07

0 Answers0