gpt4 book ai didi

python - 由于日期格式,django rest framework 列表查询自定义 json 数组结果响应

转载 作者:太空狗 更新时间:2023-10-29 20:22:24 25 4
gpt4 key购买 nike

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

这是 Rest API,问题创建于我希望它的格式如下:('%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 列表响应?

最佳答案

使用serializers django rest framework,创建一个序列化器类

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)

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)

关于python - 由于日期格式,django rest framework 列表查询自定义 json 数组结果响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47723231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com