简体   繁体   English

django rest framework序列化属性字段作为日期?

[英]django rest framework serialize property field as date?

I have this : 我有这个 :

extra_kwargs = {
    'posting_date': {'format':'%d-%m-%Y'},
    'validation_date': {'format':'%d-%m-%Y'},
    'execution_date': {'format':'%d-%m-%Y'},
    'rejection_date': {'format':'%d-%m-%Y'},
    'deadline': {'format':'%d-%m-%Y'}
}

Every thing works fine with first 4 fields since they are datetime django model field. 由于它们是datetime django模型字段,因此前4个字段的每个东西都能正常工作。 the last one (deadline) is a property and It's not treated as datetime by django serializer even if it returns a datetime so using format raises an exception. 最后一个(截止日期)是一个属性,它不被django序列化程序视为日期时间,即使它返回一个日期时间,因此使用format会引发异常。

Any solution for this issue ? 解决这个问题的任何方法?

You can always convert a string to a python datetime object, like this: 您始终可以将字符串转换为python datetime对象,如下所示:

from datetime import datetime

# strptime stands for "from string parse the (date)time"
datetime_obj = datetime.strptime('Jan 30 2017 17:00PM', '%b %d %Y %I:%M%p')

More on this here . 更多关于这里

覆盖to_representation方法以重新格式化响应数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM