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

时间:2019-06-21 10:19:59

标签: python flask nested schema marshmallow

我目前正在制作一个带有get请求的API,以返回2个模型的联合json数据,这些数据使用flask,sqlalchemy和flask-sqlalchemy(进行查询)和flask-marshmallow(进行序列化为JSON)具有关联性

我的模特:

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")

我的模式:

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)

Recording模型具有许多RecordingResult(外键为record_id)

然后我使用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

通过邮递员发送请求后,我得到了以下错误消息:

  

AttributeError:“ recording_id”不是有效字段   对于[id:1]。 // Werkzeug调试器

然后在控制台中出现此错误:

  

'“ {0}”不是{1}的有效字段。'。format(key,obj))app_1
  | AttributeError:“ recording_id”不是[id:1]的有效字段。

我打印了查询并得到了结果,但是当我尝试使用模式时,该字段似乎无效。我跟随长颈瓶棉花糖的文档使用嵌套对象,我做错了什么?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

我将架构更改为:

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) 

现在它起作用了,因为我没有在其中输入many = True参数