【问题标题】:Django-notifications serialize target rest frameworkDjango-notifications 序列化目标休息框架
【发布时间】:2019-06-14 23:55:37
【问题描述】:

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

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

序列化器.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)  

如何使目标不为空?

【问题讨论】:

    标签: django-rest-framework django-notification


    【解决方案1】:

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

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

    如果我想要一个非空目标,我应该指定一个类似

    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

    【讨论】:

    • 你好,能不能把生成你上面贴的json的视图代码分享一下?
    • 添加了一条评论。
    猜你喜欢
    • 2014-10-09
    • 2013-04-08
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2016-04-25
    相关资源
    最近更新 更多