django-rest-framework - Django-notifications 序列化目标休息框架
问题描述
我正在尝试将 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)
如何使目标不为空?
解决方案
原来目标是空的,因为这就是我在模型中创建通知的方式
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
推荐阅读
- grep - Adobe InDesign GREP 跨越多行和多段
- git - Git:工作文件与上次提交不同,没有任何更改提交
- javascript - 如何通过谷歌应用脚本从 xlsx gmail 附件中提取谷歌表格中的信息
- python - 多维numpy数组中指定范围内的列匹配
- django - 属性错误“QueryDict”对象没有属性“_meta”
- r - 在knitr R Markdown中确定图形和绘图的确切位置
- angular - NativeScript - 单元测试 HttpInterceptor NSLocationStrategy 错误
- identityserver4 - Identity Server 4 和 User.Claims.Properties.Count 在客户端上始终为 0
- java - MongoDB Java驱动程序@BsonDiscriminator不工作
- python - 将 div 类中的信息提取到 json 对象(或数据框)