我正在尝试从看起来像这样的数据库中返回所有关键字的列表
[
'foo',
'bar',
'baz',
]
模型
class Keyword(db.Model, SurrogatePK):
__tablename__ = 'keywords'
keyword = Column(db.Text, nullable=False, unique=True)
def __repr__(self):
"""Represent instance as a unique string."""
return '<Keyword({keyword})>'.format(keyword=self.keyword)
架构
class KeywordSchema(ma.ModelSchema):
class Meta:
model = Keyword
然后,
keywords_schema = KeywordSchema(many=True, only='keyword')
路线
class Keywords(Resource):
def get(self):
'''Head to http://localhost:5000/api/v1/keywords
Returns a list of all keywords.
'''
keywords = Keyword.query.all()
result = keywords_schema.dump(keywords)
return jsonify({'keywords': result})
这会引发“ AttributeError”
部分跟踪
File "C:\Users\ddonovan\DHG\web\flask-research\Query-Metadata\metadata\views.py", line 33, in get
result = keywords_schema.dump(keywords)
File "c:\users\ddonovan\.edm\envs\flask\lib\site-packages\marshmallow\schema.py", line 491, in dump
self._update_fields(processed_obj, many=many)
File "c:\users\ddonovan\.edm\envs\flask\lib\site-packages\marshmallow\schema.py", line 760, in _update_fields
ret = self.__filter_fields(field_names, obj, many=many)
File "c:\users\ddonovan\.edm\envs\flask\lib\site-packages\marshmallow\schema.py", line 834, in __filter_fields
'"{0}" is not a valid field for {1}.'.format(key, obj))
AttributeError: "w" is not a valid field for <Keyword(numpy)>
答案 0 :(得分:0)
我的KeywordSchema实例必须为keywords_schema = KeywordSchema(many=True, only=['keyword'])
然后在我的端点
class Keywords(Resource):
def get(self):
'''Head to http://localhost:5000/api/v1/keywords
Returns a list of all keywords.
Example Output:
[
"foo",
"bar",
"baz"
]
'''
keywords = Keyword.query.all()
result = keywords_schema.dump(keywords)
return jsonify([d['keyword'] for d in result.data])