django rest framework list query customize json ar

2019-06-16 07:23发布

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.

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

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')}

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

Question: How can I have a json list response with the formatting I want ?

2条回答
走好不送
2楼-- · 2019-06-16 07:33

You can try to define time formt setting in project settings.py file,there are 4 types of time format setting:DATE_FORMAT、DATETIME_FORMAT、TIME_FORMAT 、 SHORT_DATETIME_FORMAT.

for example:

DATE_FORMAT = 'Y-m-d H:i'

if you use DRF, You also can use this method to define project global date format settings.

You can get ref from https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-DATETIME_FORMAT

查看更多
放我归山
3楼-- · 2019-06-16 07:50

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)  

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)

查看更多
登录 后发表回答