Search code examples
mongoenginemarshmallow

flask-marshmallow custom fields


I use flask-marshmallow and mongoengine.

Also flask-restplus for my API server.

Here is my 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)

When I access to /article, it's result like this ->

{
  "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"
  ]
}

in "views", ip will be added who read article.

But I want to count of all the list of views and include it to my result.

The result I wanted is here.

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

I'm new at flask-marshmallow so I'm so confused how can I solve this issue.

Thanks.


Solution

  • Maybe you can try like this:

    class BoardSchemaCustom(ma.ModelSchema):
        class Meta:
            model = Board
    
        views = ma.fields.method(deserialize="_custom_serializer")
    
        def _custom_serializer(self, obj):
            return len(obj.views)
    

    Create instance of your custom schema:

    custom_board_schema = BoardSchemaCustom()
    

    and dump it:

    dump, errors = custom_board_schema.schema.dump(Board.query.first())
    >>> dump