Django-notifications 序列化目标 rest 框架

Django-notifications serialize target rest framework

我正在尝试将 Django 通知添加到我的 drf 项目中。我在到达端点时得到响应:

[
    {
        "recipient": {
            "id": 274,
            "username": "harry",
            "first_name": "Harry",
            "last_name": "Moreno"
        },
        "unread": true,
        "target": null,
        "verb": "invite approved"
    }
]

serializers.py

class GenericNotificationRelatedField(serializers.RelatedField):                                                          
    User = get_user_model()                                                                                               

    def to_representation(self, value):                                                                                   
        if isinstance(value, Invite):                                                                                     
            serializer = InviteSerializer(value)                                                                          
        if isinstance(value, User):                                                                                       
            serializer = UserSerializer(value)                                                                        
        return serializer.data                                                                                            


class NotificationSerializer(serializers.Serializer):                                                                     
    recipient = UserSerializer(read_only=True)                                                                            
    unread = serializers.BooleanField(read_only=True)                                                                     
    target = GenericNotificationRelatedField(read_only=True)  

如何使目标不为空?

原来目标是空的,因为这就是我在模型中创建通知的方式

notify.send(user, recipient=user, verb='you reached level 10')

如果我想要一个 non-null 目标,我应该指定一个

notify.send(user, recipient=user, target=user, verb='you reached level 10')

注意:问题中没有生成json的django视图。 在我们的 urls.py 中,我们将路由连接到应用程序的通知视图。

    path(
      "alerts/",
      views.NotificationViewSet.as_view({"get": "list"}),
      name="notifications",
    ),

查看安装说明https://github.com/django-notifications/django-notifications#installation