Search code examples
pythonflasknestedschemamarshmallow

flask-marshmallow nested schema doesn't apply


I'm currently making an API with get request to return a joined json data of 2 models which has a relationship using flask, sqlalchemy and flask-sqlalchemy(to query) and flask-marshmallow (to serialization to JSON)

My models:

class Recording(Base):
    __tablename__ = 'recordings'

    id = Column(Integer, primary_key=True)
    filepath = Column(String, nullable=False)

    language_id = Column(Integer, ForeignKey('languages.id'), nullable=False)
    language = relationship("Language", back_populates="recordings")

    user_id = Column(Integer, ForeignKey('users.id'), nullable=False)
    user = relationship("User", back_populates="recordings")

    created_at = Column(DateTime, nullable=False, default=func.now())
    updated_at = Column(DateTime, nullable=False,
                        default=func.now(), onupdate=func.now())
    deletedd_at = Column(DateTime, nullable=True)

    def __repr__(self):
        return 'id: {}'.format(self.id)

User.recordings = relationship("Recording", order_by=Recording.id, back_populates="user")
Language.recordings = relationship("Recording", order_by=Recording.id, back_populates="language")


class RecordingResult(Base):
    __tablename__ = 'recording_results'

    id = Column(Integer, primary_key=True)
    is_with_dictionary = Column(Boolean, default=False)
    result = Column(String, nullable=True)
    run_time = Column(Float, default=0.0)

    recording_id = Column(Integer, ForeignKey('recordings.id'), nullable=False)
    recording = relationship("Recording", back_populates="recording_results", lazy="joined")

    speech_service_id = Column(Integer, ForeignKey('speech_services.id'), nullable=False)
    speech_service = relationship("SpeechService", back_populates="recording_results")

    created_at = Column(DateTime, nullable=False, default=func.now())
    updated_at = Column(DateTime, nullable=False,
                        default=func.now(), onupdate=func.now())
    deletedd_at = Column(DateTime, nullable=True)

    def __repr__(self):
        return 'id: {}'.format(self.id)

Recording.recording_results = relationship("RecordingResult", order_by=RecordingResult.id, back_populates="recording", lazy="joined")
SpeechService.recording_results = relationship("RecordingResult", order_by=RecordingResult.id, back_populates="speech_service")

My schemas :

class RecordingResultItemSchema(ma.Schema):
    class Meta:
        model = RecordingResult
        fields = ('id', 'is_with_dictionary', 'result', 'run_time', 'recording_id', 'speech_service_id')

class RecordingItemSchema(ma.Schema):
    class Meta:
        model = Recording
        fields = ('id', 'filepath', 'language_id', 'user_id', 'recording_results')  
    recording_results = ma.Nested(RecordingResultItemSchema)
recording_item_schema = RecordingItemSchema()
recording_items_schema = RecordingItemSchema(many=True)
recording_result_item_schema = RecordingResultItemSchema()
recording_result_items_schema = RecordingResultItemSchema(many=True)

The Recording model has many RecordingResult (foreign key is recording_id)

And i used this query in API using 'lazy' of sqlalchemy to get joined data of 2 models:

@app.route('/recording', methods=['GET'])
def get_recording_item():
    if db.session.query(Recording).options(joinedload(Recording.recording_results)).all():
        recording_list = db.session.query(Recording).options(joinedload(Recording.recording_results)).all()
        result = recording_items_schema.dump(recording_list)
        return jsonify(result.data), 200
    else:
        return jsonify(msg="Object not found"), 400

After sending request through postman i got this in error:

AttributeError: "recording_id" is not a valid field for [id: 1]. // Werkzeug Debugger

And in the console i got this error:

'"{0}" is not a valid field for {1}.'.format(key, obj)) app_1
| AttributeError: "recording_id" is not a valid field for [id: 1].

I printed the query and got the result but when I try to use schemas the fields seem to not be valid. I followed the docs of flask-marshmallow to use a nested object, what did I do wrong? Any helps would be appreciate


Solution

  • I changed the schema to:

    class RecordingResultItemSchema(ma.Schema):
        class Meta:
            model = RecordingResult
            fields = ('id', 'is_with_dictionary', 'result', 'run_time', 'recording_id', 'speech_service_id')
    
    class RecordingItemSchema(ma.Schema):
        class Meta:
            model = Recording
            fields = ('id', 'filepath', 'language_id', 'user_id', 'recording_results')  
        recording_results = ma.Nested(RecordingResultItemSchema, many=True) 
    

    and now it worked, because i didn't put the many=True parameter in