gpt4 book ai didi

django-rest-framework - 如何在使用 stream-django 和 django rest 框架进行扩充的过程中序列化对象?

转载 作者:行者123 更新时间:2023-12-04 08:38:25 25 4
gpt4 key购买 nike

我将流 django 与 django REST 框架一起使用,并且丰富的事件在从丰富返回的对象上抛出“不可序列化的 JSON”,这是预期的,因为它们没有经过任何序列化。

我如何自定义扩充过程,以便它从我的 drf 序列化程序返回一个序列化的对象,而不是对象本身?

一些示例数据,不是 丰富:

"is_seen": false,
"is_read": false,
"group": "19931_2016-04-04",
"created_at": "2016-04-04T08:53:42.601",
"updated_at": "2016-04-04T11:33:26.140",
"id": "0bc8c85a-fa59-11e5-8080-800005683205",
"verb": "message",
"activities": [
{
"origin": null,
"verb": "message",
"time": "2016-04-04T11:33:26.140",
"id": "0bc8c85a-fa59-11e5-8080-800005683205",
"foreign_id": "chat.Message:6",
"target": null,
"to": [
"notification:1"
],
"actor": "auth.User:1",
"object": "chat.Message:6"
}

风景:
def get(self, request, format=None):
user = request.user
enricher = Enrich()
feed = feed_manager.get_notification_feed(user.id)
notifications = feed.get(limit=5)['results']
enriched_activities=enricher.enrich_aggregated_activities(notifications)
return Response(enriched_activities)

最佳答案

我通过执行以下操作解决了它:

返回序列化程序类的模型上的属性标记

@property
def activity_object_serializer_class(self):
from .serializers import FooSerializer
return FooSerializer

然后用它来序列化丰富的事件。支持嵌套。
@staticmethod
def get_serialized_object_or_str(obj):
if hasattr(obj, 'activity_object_serializer_class'):
obj = obj.activity_object_serializer_class(obj).data
else:
obj = str(obj) # Could also raise exception here
return obj

def serialize_activities(self, activities):
for activity in activities:
for a in activity['activities']:
a['object'] = self.get_serialized_object_or_str(a['object'])
# The actor is always a auth.User in our case
a['actor'] = UserSerializer(a['actor']).data
return activities

和观点:
def get(self, request, format=None):
user = request.user
enricher = Enrich()
feed = feed_manager.get_notification_feed(user.id)
notifications = feed.get(limit=5)['results']
enriched_activities = enricher.enrich_aggregated_activities(notifications)
serialized_activities = self.serialize_activities(enriched_activities)
return Response(serialized_activities)

关于django-rest-framework - 如何在使用 stream-django 和 django rest 框架进行扩充的过程中序列化对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36420024/

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