【发布时间】:2020-08-13 10:05:28
【问题描述】:
我在序列化第 3 方包 (django-organizations) 时遇到问题,因为我想以 JSON 格式接收上下文。
类本身如下所示:
class OrganizationUserMixin(OrganizationMixin, JSONResponseMixin):
"""Mixin used like a SingleObjectMixin to fetch an organization user"""
user_model = OrganizationUser
org_user_context_name = 'organization_user'
def get_user_model(self):
return self.user_model
def get_context_data(self, **kwargs):
kwargs = super(OrganizationUserMixin, self).get_context_data(**kwargs)
kwargs.update({self.org_user_context_name: self.object,
self.org_context_name: self.object.organization})
return kwargs
def get_object(self):
""" Returns the OrganizationUser object based on the primary keys for both
the organization and the organization user.
"""
if hasattr(self, 'organization_user'):
return self.organization_user
organization_pk = self.kwargs.get('organization_pk', None)
user_pk = self.kwargs.get('user_pk', None)
self.organization_user = get_object_or_404(
self.get_user_model().objects.select_related(),
user__pk=user_pk, organization__pk=organization_pk)
return self.organization_user
我正在尝试将此自定义 JSONResponseMixin 传递给我的 OrganizationUserMixin 类:
class JSONResponseMixin:
"""
A mixin that can be used to render a JSON response.
"""
def render_to_json_response(self, context, **response_kwargs):
"""
Returns a JSON response, transforming 'context' to make the payload.
"""
return JsonResponse(
self.get_data(context),
**response_kwargs
)
def get_data(self, context):
print(context)
return context
然后像这样覆盖OrganizationUserMixin 中的render_to_response:
def render_to_response(self, context, **response_kwargs):
return self.render_to_json_response(context, **response_kwargs)
如果我打印context
看起来像这样
# {
# 'object': <OrganizationUser: Erik (MyOrgName)>,
# 'organizationuser': <OrganizationUser: Erik (MyOrgName)>,
# 'organization': <Organization: MyOrgName>,
# 'view': <organizations.views.OrganizationUserDetail object at 0x1091a3ac0>,
# 'organization_user': <OrganizationUser: Erik (MyOrgName)>
# }
我得到的错误信息是TypeError: Object of type OrganizationUser is not JSON serializable
如何在我的 JSONResponseMixin 中序列化 context?
【问题讨论】:
-
您希望从序列化中得到什么数据?是模型的
__unicode__()值吗?然后您可以检查上下文字典中每个值的类型,如果它是一个对象,请将其替换为__unicode__()的调用。话虽如此,您在这里最需要的可能是使用序列化程序并定义要序列化程序的字段,通用JsonResponseMixin是不够的。 -
我希望将上下文中的数据转换为 JSON 格式,例如
'organization_user': <OrganizationUser: Erik (MyOrgName)>,这样我就可以在页面上做一些 AJAX 而不是使用常规模板视图 -
您评论中的
<>表明这是一个python 对象,您不能在Json 中有python 对象。你的意思是字符串OrganizationUser: Erik (MyOrgName)? -
是的,实际的对象就是我想要 JSONify 的对象
-
好的,我现在明白了,查看我刚刚发布的答案,如果您还有其他问题,请告诉我
标签: django django-class-based-views django-serializer