如何在 Django 通道休息框架中订阅模型的所有实例?

How to subscribe to all instances of a model in django channels rest framework?

我想将 API 的行为更改为 JSON 触发(从浏览器调用),但我什至无法从 Python 调用它客户由于我对 Python.

的了解有限

有人可以帮助我如何像 manual 节目那样做吗?这是我的简单客户端:

class GenericAsyncAPIConsumerWith(GenericAsyncAPIConsumer):
    async def websocket_connect(self, message):

        # Super Save
        await super().websocket_connect(message)

        # Initialized operation
        await self.model_activity.subscribe()


class UserConsumer(ObserverModelInstanceMixin, GenericAsyncAPIConsumerWith):
    queryset = Course.objects.order_by("-start_time")
    serializer_class = UserSerializer
    # permission_classes = [IsAuthenticated]


@model_observer(User)
async def model_activity(self, message, observer=None, **kwargs):
    # send activity to your frontend
    await self.send_json(message)    

我觉得文档有点不清楚,这是解决方案,也做了pr。

class ModelConsumerObserver(AsyncAPIConsumer):
    async def accept(self, **kwargs):
        await super().accept()
        await self.model_change.subscribe()
    
    @model_observer(models.Test)
    async def model_change(self, message, **kwargs):
        await self.send_json(message)

从那时起,websocket 会将模型更改推送到客户端

当我这样做时,我没有收到任何关于更改的信息。我成功连接到路由,但是当我修改产品时,我没有收到从服务器到客户端的任何消息。

这是我的消费者:

class ProductConsumer(AsyncAPIConsumer):
    async def accept(self, **kwargs):
        await super().accept(** kwargs)
        await self.model_change.subscribe()

    @model_observer(Product)
    async def model_change(self, message, **kwargs):
        await self.send_json(message)