默认情况下,Django DateTime文件保存并显示数据中的秒、毫秒和额外信息,例如,它保存并显示的日期如下:
2018-07-21 05:27:29.736956+00:00
在尝试检索数据时,是否有任何方法或全局函数忽略额外信息而只获取日期和时间?就像
2018-07-21 05:27:29
型号:
class Enrolled(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
product = models.ForeignKey(Product, on_delete=models.CASCADE, to_field='product_id',
related_name='enroll')
created_date = models.DateTimeField(auto_now_add=True)
系列化器
class EnrolledSerializer(ModelSerializer):
ptitle = serializers.SerializerMethodField()
instructor = serializers.SerializerMethodField()
instructorid = serializers.SerializerMethodField()
pslug = serializers.SerializerMethodField()
def get_instructor(self, object):
return object.product.author.username
def get_instructorid(self, object):
return object.product.author.id
def get_ptitle(self, obj):
return obj.product.title
def get_pslug(self, obj):
return obj.product.slug
class Meta:
model = Enrolled
fields = [
'id',
'user',
'product',
'ptitle',
'instructorid',
'pslug',
'instructor',
'created_date',
]
read_only_fields = ['product', 'created_date', 'id', 'user', 'instructor', 'instructorid', 'pslug', 'ptitle']
//编辑:
REST_FRAMEWORK = {
'DATETIME_FORMAT': ("%Y-%m-%d %H:%M"),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
)
}
USE_I18N = False
USE_L10N = False
USE_TZ = True
似乎与Change time format in Django Views有关
使用
或者您可以按照模板过滤器https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#std:templatefilter-date的要求在视图中格式化datetime
通过设置所有日期时间字段,可以为
created_date
设置日期时间格式:仅适用于当前序列化程序,如果其他字段只是引用,则可以使用
source
选项,例如:阅读文档:date-and-time-fields和source。你知道吗
相关问题 更多 >
编程相关推荐