直接在Flask-Peewee中显示ForeignKeyField

时间:2014-04-02 12:38:08

标签: python flask-peewee

我使用Flask-Peewee API库设置了一个API:

class ActivityResource(RestResource):
    exclude = ('id', 'course')

class CourseResource(RestResource):
    exclude = ('id')

class SessionResource(RestResource):
    def get_query(self):
        identifier = get_identifier()
        student = Student.get(Student.identifier == identifier)
        from = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
        to = datetime(2014, 6, 15)
        return self.model.select().where(Session.date.between(from, to)).join(Activity).join(Course).join(StuCouRel).join(Student).where(Student.id == student.id).order_by(Session.date, Session.begin_time, Session.end_time)
    paginate_by = None
    include_resources = {
    'activity': ActivityResource,
    'course': CourseResource
    }
    exclude = ('id')

这将输出如下内容:

[
  {
    "duration": 7200,
    "activity": {
      "name": "MyActivityName"
    },
    "course": {
      "name": "MyCourseName"
    },
    "end_time": "18:00",
    "begin_time": "16:00",
    "date": "03-04-2014"
  },
  ...
]
然而,我想得到的是:

[
 {
   "duration": 7200,
   "activity": "MyActivityName",
   "course": "MyCourseName",
   "end_time": "18:00",
   "begin_time": "16:00",
   "date": "03-04-2014"
  },
  ...
]

我已阅读文档并尝试阅读the source code itself,但我无法弄清楚如何使其发挥作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我使用prepare_data() hook:

完成了这项工作
def prepare_data(self, obj, data):
        data["activity"] = obj.activity.name
        data["course"] = obj.course.name
        return data