4

我将stream-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)
4

2 回答 2

3

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

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

@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)
于 2016-04-05T11:51:03.523 回答
0

丰富步骤将字符串引用替换为完整的 Django 模型实例。

例如:字符串“chat.Message:6”被替换为chat.models.Message(same as Message.objects.get(pk=6)) 的实例。

默认情况下,DRF 不知道如何序列化 Django 模型,并因序列化错误而失败。幸运的是,在使用 DRF 时,序列化模型是一项非常简单的任务。有一个特定于 Django 模型的内置序列化程序类 ( serializers.ModelSerializer)。

DRF 的文档在这里详细解释了这个过程:http: //www.django-rest-framework.org/api-guide/serializers/#modelserializer

在您的情况下,您可能需要使用嵌套序列化并使字段的序列化变得object智能(该字段可以包含对不同类型对象的引用)。

Github 上有一个未解决的问题:https ://github.com/GetStream/stream-django/issues/38 。理想情况下,这是库将作为帮助程序/示例提供的东西,因此任何代码贡献/输入都将有助于实现这一目标。

于 2016-04-05T09:48:10.487 回答