Flask-restful 如何在 mongoengine 的 reference_field 中`marshal_with()` 数据?

Flask-restful How to `marshal_with()` data in reference_field of mongoengine?

我使用 Flask-restfulMongoEngine,我想在 JSON 中显示我模型的 ReferenceField 中的数据。

我有这 2 个模型,RoomModel 有一个 ReferenceFieldUserModel

class RoomModel(Document):
    meta = {'allow_inheritance': True}

    room_name = StringField()
    created_by = ReferenceField(UserModel)

class UserModel(Document):

    username = StringField()
    email = StringField()

我想 marshal_with() 从 mongoengine 查询到响应的所有数据,所以我这样做了:

     room_model_fields = {
        'room_name': fields.String,
        'created_by': fields.String(attribute=UserModel._id)
    }

    room_model_fields_format = {
        'rooms': fields.List(fields.Nested(room_model_fields))
    }


    @staticmethod
    @marshal_with(room_model_fields_format)
    def get():
        room = RoomModel.objects().all() 
        return {'rooms': room},200

我收到这样的回复:

{
 rooms": [
    {
      "room_name": "mobile_legend",
      "created_by": "UserModel object" <<--Now: This only return a string with "UserModel object"
      "created_by": "SOME_ID_STRING"  <<-- THIS IS WHAT I WANT
    }
  ]
}

我看到我的数据库,它有一个带有 created_by: SOME_ID_STRING_HERE 的字段,我希望在响应中显示 SOME_ID_STRING 而不是 "UserModel object" 字符串。

我该如何解决这个问题?

您需要使用 attribute='created_by.id'。请参阅以下示例:

from mongoengine import StringField
from flask_restful import fields, marshal_with

class Car(Document):
    brand = StringField()

class User(Document):
    car = ReferenceField(Car)
    name = StringField()

car = Car(brand='VW').save()
user = User(car=car, name='John Doe').save()

@marshal_with({'name': fields.String, 'id': fields.String, 'car_id': fields.String(attribute='car.id')})
def get():
    return user

print(dict(get()))    # {'car_id': u'5e124e83aa7a179157418ab2', 'name': u'John Doe', 'id': u'5e124e83aa7a179157418ab3'}