0

Let me backtrack a little - The problem is actually happening in initializing a Mentor using the MentorSchema we have:

class Mentor(db.Model):
    __tablename__ = 'mentors'
    id = db.Column(db.Integer, primary_key=True)
    id_project42 = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)
    id_user42 = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    finalmark = db.Column(db.Integer, nullable=False, server_default=0)
    totalappointments = db.Column(db.Integer, nullable=False, server_default=0)

    def __init__(self, id_project42, id_user42, finalmark):
        self.id_project42 = id_project42
        self.id_user42 = id_user42
        self.finalmark = finalmark
        self.totalappointments = 0

class MentorSchema(ma.ModelSchema):
    class Meta:
        model = Mentor

So if I have d = { "id_project42": 101, "id_user42": 57, "finalmark": 86},and I attempt a mentor_schema.dump(d)then the id_project42 and id_user42 both disappear and I get an error telling me that:TypeError: __init__() missing 2 required positional arguments: 'id_project42' and 'id_user42'

The actual code we are using is here:

class ApiUserInit(Resource):
    def post(self, userId):
        data = Api42.userProjects(userId)    # Returns a list of dicts
        if data is None:
            return formatError('Error', 'No projects found for user')
        for d in data:
            print(d)    # prints {"id_project42": 101, "id_user42": 57, "finalmark": 86}
            mentor_schema = MentorSchema()
            newMentor, errors = mentor_schema.load(d) # Only loading the "finalmark"!!!!!!
            if errors:
                return internalServiceError()
            db.session.add(newMentor)
        db.session.commit()
        return {"status":"mentor initialization successful"}, 201

Please let me know if there's an issue with the way I'm using the Schema as well.

Brendan
  • 1
  • 1

1 Answers1

0

By default, foreign keys will not be included when you call your schema’s dump method. You need to set include_fk = True on your schema Meta class:

class MentorSchema(ma.ModelSchema):
    class Meta:
        model = Mentor
        include_fk = True

More info: marshmallow-sqlalchemy API reference

atwalsh
  • 3,622
  • 1
  • 19
  • 38