Django Rest框架列表查询由于日期格式而自定义json数组结果响应 [英] django rest framework list query customize json array result response because of date formatting

查看:138
本文介绍了Django Rest框架列表查询由于日期格式而自定义json数组结果响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个Django REST API,我想为json响应自定义列表查询结果。原因是因为日期格式以及其他可能的格式。

I have this Django REST API that I want to customize the list query result for the json response. The reason is because of date formatting and potentially other formatting as well.

这是Rest API,问题是created_at,我希望它采用以下格式:('% Y-%m-%d%H:%M')。以下代码没有任何格式,它只会列出结果并创建一个json。

This is the Rest API, the issue is created_at I want it to formatted like this: ('%Y-%m-%d %H:%M'). The following code doesn't have any formatting, it will just list and create a json on the result.

@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。

This is the model. Notice I have .as_dict() function. For individual record like using emp = Employee.objects.get(id=6), I can do like this emp.as_dict() and the result will have the formatted date in 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响应结果。请注意日期未格式化。

This is the json response result of the list. Notice the date is not formatted.

[
  {
    "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"
  }  
]

问题:如何使用

推荐答案

使用 序列化器 ,创建一个序列化器类

Use serializers of django rest framework, create a serializer class

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")

现在使用序列化程序类解析员工的查询集。

Now parse your employees queryset using serializer class.

@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格式明确表示
指定格式,或特殊字符串 iso-8601 ,表示
表示 ISO 8601 样式的日期时间。 (例如
2013-01-29T12:34:56.000000Z

Format strings may either be Python strftime formats which explicitly specify the format, or the special string iso-8601, which indicates that ISO 8601 style datetimes should be used. (eg 2013-01-29T12:34:56.000000Z)

这篇关于Django Rest框架列表查询由于日期格式而自定义json数组结果响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆