0

我正在尝试将 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)  

如何使目标不为空?

4

1 回答 1

3

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

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

于 2019-06-15T00:08:01.203 回答