我有这个Django REST API,我想自定义json响应的列表查询结果。原因是因为日期格式化以及可能的其他格式化。
这是Rest API,问题是created_at我希望它的格式如下:('%Y-%m-%d%H:%M')。以下代码没有任何格式,它只会列出并在结果上创建一个json。
@api_view(['POST'])
def employee_get_list_by_page(request):
val_params = ["id", "username","first_name","last_name","created_at"]
employee_list = Employee.objects.all().values(*val_params).order_by('id')
page = request.GET.get('page', request.POST['page'])
paginator = Paginator(employee_list, request.POST['page_limit'])
try:
employees = paginator.page(page)
except PageNotAnInteger:
employees = paginator.page(request.POST['page'])
except EmptyPage:
employees = paginator.page(paginator.num_pages)
return Response(list(employees), status=status.HTTP_200_OK)
这是模型。注意我有.as_dict()函数。对于个人记录,比如使用emp = Employee.objects.get(id = 6),我可以这样做emp.as_dict(),结果将在created_at中具有格式化日期。
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='employee')
company = models.ForeignKey(Company)
username = models.CharField(max_length=30, blank=False)
first_name = models.CharField(max_length=30, blank=False)
last_name = models.CharField(max_length=30, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.user.username
def as_dict(self):
return {"id": "%d" % self.id,
"username": self.username if self.username else "",
"first_name": self.first_name if self.first_name else "",
"last_name": self.last_name if self.last_name else "",
"created_at":self.created_at.strftime('%Y-%m-%d %H:%M')}
这是列表的json响应结果。请注意,日期未格式化。
[
{
"id": 7,
"username": "mick",
"first_name": "zack",
"last_name": "ray",
"created_at": "2017-12-07T10:09:28.376427Z" <-- I want this to be ('%Y-%m-%d %H:%M')
},
{
"id": 8,
"username": "hu",
"first_name": "rar",
"last_name": "baw",
"created_at": "2017-12-10T09:08:27.473997Z"
}
]
问题:如何使用我想要的格式获得json列表响应?
使用django rest框架的serializers
,创建一个序列化器类
from rest_framework import serializers
class EmployeeSerializer(serializers.ModelSerializer):
created_at = serializers.DateTimeField(format='%Y-%m-%d %H:%M')
class Meta:
model = Employee
fields = ("id", "username", "first_name", "last_name", "created_at")
现在使用序列化程序类解析您的员工查询集。
@api_view(['POST'])
def employee_get_list_by_page(request):
employees = Employee.objects.all().values(*val_params).order_by('id')
serializer = EmployeeSerializer(employees, many=True)
# rest of your code
...
return Response(serializer.data, status=status.HTTP_200_OK)
格式字符串可以是明确指定格式的Python strftime formats,也可以是特殊字符串
iso-8601
,它表示应该使用ISO 8601
样式日期时间。 (例如2013-01-29T12:34:56.000000Z
)
您可以尝试在project settings.py文件中定义时间表设置,有4种类型的时间格式设置:DATE_FORMAT,DATETIME_FORMAT,TIME_FORMAT,SHORT_DATETIME_FORMAT。
例如:
DATE_FORMAT = 'Y-m-d H:i'
如果使用DRF,还可以使用此方法定义项目全局日期格式设置。
你可以从https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-DATETIME_FORMAT获得参考