烧瓶棉花糖自定义字段

flask-marshmallow custom fields

我使用 flask-marshmallow 和 mongoengine。

还有我的 API 服务器的 flask-restplus。

这是我的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": "\ud14c\uc2a4\ud2b8", 
  "views": [
    "127.0.0.1"
  ]
}

"views"中,阅读文章的人将添加ip

但我想计算所有视图列表并将其包含在我的结果中。

我要的结果来了

{
  "body": "123", 
  "created_at": "2018-08-20T00:00:00+00:00", 
  "no": 1, 
  "tags": [
    "MySQL", 
    "C"
  ], 
  "title": "\ud14c\uc2a4\ud2b8", 
  "views": 20
}

我是 flask-marshmallow 的新手,所以我很困惑如何解决这个问题。

谢谢。

也许你可以这样试试:

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

我也遇到了同样的问题。我的代码在安装 marshmallow-sqlalchemy

后工作
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))