我使用烧瓶棉花糖和mongoengine。
还有我的API服务器的烧瓶休息加。
这是我的 api.py
class BoardSchema(ma.Schema):
class Meta:
fields = ('no', 'title', 'body', 'tags', 'created_at', 'views')
board_schema = BoardSchema()
boards_schema = BoardSchema(many=True)
class ArticleList(Resource):
def get(self):
articles = Board.objects.all()
return boards_schema.jsonify(articles)
model.py
from datetime import datetime
from mongoengine import *
from config import DB_NAME
connect(DB_NAME)
class Board(Document):
d = datetime.now()
date = "{}-{}-{}".format(d.year, d.month, d.day)
no = SequenceField()
title = StringField(required=True)
body = StringField(required=True)
tags = ListField(StringField())
likes = ListField(StringField())
views = ListField(StringField())
password = StringField(required=True)
created_at = DateTimeField(default=date)
updated_at = DateTimeField(default=date)
当我访问/article 时,结果是这样的 ->
{
"body": "123",
"created_at": "2018-08-20T00:00:00+00:00",
"no": 1,
"tags": [
"MySQL",
"C"
],
"title": "ud14cuc2a4ud2b8",
"views": [
"127.0.0.1"
]
}
在"views"
,将添加阅读文章的IP。
但是我想计算所有视图列表并将其包含在我的结果中。
我想要的结果就在这里。
{
"body": "123",
"created_at": "2018-08-20T00:00:00+00:00",
"no": 1,
"tags": [
"MySQL",
"C"
],
"title": "ud14cuc2a4ud2b8",
"views": 20
}
我是烧瓶棉花糖的新手,所以我很困惑如何解决这个问题。
谢谢。
也许你可以这样尝试:
class BoardSchemaCustom(ma.ModelSchema):
class Meta:
model = Board
views = ma.fields.method(deserialize="_custom_serializer")
def _custom_serializer(self, obj):
return len(obj.views)
创建自定义架构的实例:
custom_board_schema = BoardSchemaCustom()
并转储它:
dump, errors = custom_board_schema.schema.dump(Board.query.first())
>>> dump
我有同样的问题。 我的代码在安装棉花糖-SQLllChemy后工作
pip install marshmallow-sqlalchemy
参见官方文档 https://flask-marshmallow.readthedocs.io/en/latest/
下面的代码片段也可以工作:
class BoardSchemaCustom(ma.ModelSchema):
class Meta:
model = Board
views = ma.fields.Function(lambda obj: len(obj.views))