只是为了扩展@luke_aus 的答案,如果您正在使用 ResourceBindings,您也可以这样做,只有“拥有”对象的用户才能检索这些更新:
就像@luke_aus 回答一样,我们将用户注册到它自己的组中,我们可以在其中发布仅对该用户可见的操作( update
, )等:create
from channels.auth import channel_session_user_from_http,
from channels import Group
@channel_session_user_from_http
def ws_connect(message):
Group("user-%s" % message.user).add(message.reply_channel)
现在我们可以更改相应的绑定,使其仅在绑定对象属于该用户时发布更改,假设模型如下:
class SomeUserOwnedObject(models.Model):
owner = models.ForeignKey(User)
现在我们可以将此模型绑定到我们的用户组,所有操作(更新、创建等)将只发布给这个用户:
class SomeUserOwnedObjectBinding(ResourceBinding):
# your binding might look like this:
model = SomeUserOwnedObject
stream = 'someuserownedobject'
serializer_class = SomeUserOwnedObjectSerializer
queryset = SomeUserOwnedObject.objects.all()
# here's the magic to only publish to this user's group
@classmethod
def group_names(cls, instance, action):
# note that this will also override all other model bindings
# like `someuserownedobject-update` `someuserownedobject-create` etc
return ['user-%s' % instance.owner.pk]