我正在尝试为包含分页的列表创建一个Django API但是有这个错误
TypeError: Object of type 'Page' is not JSON serializable
以下是我的API代码:
@api_view(['POST'])
def employee_get_list_by_page(request):
# ----- YAML below for Swagger -----
"""
description: employee_get_list_by_page
parameters:
- name: token
type: string
required: true
location: form
- name: page
type: string
required: true
location: form
- name: page_limit
type: string
required: true
location: form
"""
token = request.POST['token']
try:
auth_employee = AuthEmployeeSessionToken.objects.get(token=token)
except AuthEmployeeSessionToken.DoesNotExist:
return Response("Invalid Token", status=status.HTTP_406_NOT_ACCEPTABLE)
employee_list = Employee.objects.filter(company = auth_employee.employee.company.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(employees,status=status.HTTP_200_OK) <-- passing employees probably cause this error that employees as Page is not JSON serializable.
这是我的模型https://gist.github.com/axilaris/89b2ac6a7762f428ad715f4916f43967。 as_dict通知我有这个.as_dict()创建我的json响应。我将它用于单个请求但是对于列表我不确定它是如何完成的。
答案 0 :(得分:3)
我只是想重新创建它,我看到了一些解决方法。
首先,JSON将无法解析Page对象,也无法解析page.object_list
属性下的QuerySet。它会说"Object of type 'Employee' is not JSON serialisable"
。
为了解决这个问题,我试试:
employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).values().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)
首先,我们在employees查询集上使用.values()
,因为可以使用list(employees)
解析此调用的结果ValuesQuerySet。在Page类中,他们在返回任何结果之前以这种方式评估实例内的对象列表。
最后,由于JSON无法序列化Page类,我们只需调用list(Page)
即可返回列表。这是有效的,因为Page实现了__getitem__
并返回了底层的object_list。
此外,您可能会发现某些数据类型会抛出JSON序列化错误(values()
将返回DateTime字段的DateTime对象)。在我的测试中,我遇到了Object of type 'datetime' is not JSON serializable
的问题。如果发生这种情况,您需要使用不同的JSON编码器或扩展自己的编码器。 DjangoJSONEncoder可以在django.core.serializers.json.DjangoJSONEncoder中找到,并处理django中的日期时间,uuids,小数和其他常见数据类型。
编辑::您已将模型代码提及为:
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)
email = 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)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.user.username
def as_dict(self):
return {"id": "%d" % self.id,
"company": self.company.as_dict(),
"username": self.username if self.username else "",
"email": self.email if self.email else "",
"first_name": self.first_name if self.first_name else "",
"last_name": self.last_name if self.last_name else "",
"tel":self.tel if self.tel else "",
"created_at":self.created_at.strftime('%Y-%m-%d %H:%M'),
"updated_at":self.updated_at.strftime('%Y-%m-%d %H:%M')}
由于您拥有此as_dict
方法,我们可以使用此方法呈现您的员工的代表,而不是依赖.values()
。方法如下:
employee_list = Employee.objects.filter(company = auth_employee.employee.company.id).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)
# Here we map a lambda function over the queryset of Models to return the dictionary representation for each element in the list
employees_page = list(
map(lambda employee: employee.as_dict(), list(employees))
)
return Response(employees_page ,status=status.HTTP_200_OK)
答案 1 :(得分:1)
如果使用Django Rest Framework(DRF)的任何人找到了此内容,DRF serializers可以将page.object_list
序列化为JSON。当然,更好的方法是在DRF视图(集)中指定pagination_class
:https://www.django-rest-framework.org/api-guide/pagination/