简体   繁体   English

烧瓶棉花糖嵌套模式不适用

[英]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)我目前正在制作一个带有 get 请求的 API,以返回 2 个模型的连接 json 数据,这些数据使用flask、sqlalchemy 和flask-sqlalchemy(查询)和flask-marshmallow(序列化为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) Recording模型有很多RecordingResult(外键是recording_id)

And i used this query in API using 'lazy' of sqlalchemy to get joined data of 2 models:我使用 sqlalchemy 的“懒惰”在 API 中使用此查询来获取 2 个模型的连接数据:

@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]. AttributeError: "recording_id" 不是 [id: 1] 的有效字段。 // Werkzeug Debugger // Werkzeug 调试器

And in the console i got this error:在控制台中,我收到此错误:

'"{0}" is not a valid field for {1}.'.format(key, obj)) app_1 '"{0}" 不是 {1} 的有效字段。'.format(key, obj)) app_1
| | AttributeError: "recording_id" is not a valid field for [id: 1]. AttributeError: "recording_id" 不是 [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?我按照flask-marshmallow的文档使用嵌套对象,我做错了什么? Any helps would be appreciate任何帮助将不胜感激

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现在它起作用了,因为我没有将 many=True 参数放入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM