我一直在尝试在项目中实现用户特定的实时通知。虽然我能够广播实时通知,但我面临着创建用户特定频道的艰难斗争,其中选定的通知将发送给用户。就我的尝试而言,以下是我在查看了一些使用 swampdragon-auth 的示例后编写的代码片段:
路由器.py:
class NotificationRouter(ModelPubRouter):
valid_verbs = ['subscribe']
route_name = 'notifications'
model = Notification
serializer_class = NotificationSerializer
def get_query_set(self, **kwargs):
return self.model.objects.filter(user=self.connection.user)
def get_object(self, **kwargs):
return self.model.objects.get(user=self.connection.user, pk=kwargs['pk'])
def get_subscription_contexts(self, **kwargs):
return {'user__id': self.connection.user.pk}
模型.py
class Notification(SelfPublishModel, models.Model):
serializer_class = NotificationSerializer
message = models.TextField()
verb = models.CharField(null=True, default="achieved", max_length=20)
user = models.ForeignKey(settings.AUTH_USER_MODEL)
和serializer.py
class NotificationSerializer(ModelSerializer):
class Meta:
model = 'notifications.Notification'
publish_fields = ['message','verb','user']
此代码没有实现用户特定的通知执行并将消息广播给所有用户。据我所知,get_subscription_contexts 是过滤通知给选定用户的函数,但我无法用这段代码实现这一点。如果有人可以帮助我解决这个问题,那就太好了。
谢谢
喜满洲