棉花糖:从/到日期和时间的日期时间反序列化

时间:2019-08-09 19:55:03

标签: python json-api marshmallow

我有一个SQL表,用于将日期和时间数据存储为单个datetime。但是,API将字段分为单独的日期和时间。

我正在尝试使用Marshmallow(与marshmallow-jsonapi和更高版本的Flask-REST-jsonapi)来构建API,但我不知道如何将一个字段序列化为两个并反序列化两个字段作为一个字段。

这是数据库模型:

class Timeslot(db.Model):
    __tablename__ = 'timeslots'
    id = db.Column(db.Integer, primary_key=True)
    start = db.Column(db.DateTime, unique=True, nullable=False)
    end = db.Column(db.DateTime, nullable=False)
    comment = db.Column(db.String(250), nullable=False)

以及我尝试产生的输出:

{
  "data": {
    "attributes": {
      "comment": "Test slot",
      "end_date": "08/08/2019",
      "end_time": "19:30",
      "plus_one": false,
      "slug": "2019-08-08-15-00",
      "start_date": "08/08/2019",
      "start_time": "15:00"
    },
    "id": "1",
    "links": {
      "self": "/api/timeslots/2019-08-08-15-00"
    },
    "type": "timeslots"
  },
  "links": {
    "self": "/api/timeslots/2019-08-08-15-00"
  }
}

到目前为止,我已经知道了,但是反序列化无法以这种方式重建startend属性:

class TimeslotSchema(Schema):
    id = fields.Str(dump_only=True)
    start_date = fields.DateTime(format="%d/%m/%Y", attribute="start", dump_only=True)
    start_time = fields.DateTime(format="%H:%M", attribute="start", dump_only=True)
    end_date = fields.DateTime(format="%d/%m/%Y", attribute="end", dump_only=True)
    end_time = fields.DateTime(format="%H:%M", attribute="end", dump_only=True)
    plus_one = fields.Function(lambda obj: obj.start.date() < obj.end.date())
    slug = fields.Function(lambda obj: obj.start.strftime("%Y-%m-%d-%H-%M"))
    comment = fields.Str()

    class Meta:
        type_ = "timeslots"
        self_view = "event.timeslot"
        self_view_kwargs = {"timeslot_id_or_slug": "<slug>"}

有什么主意吗?我应该使用fields.Method吗?那我该如何验证?如果更好,如何使用@pre_load

0 个答案:

没有答案
相关问题