Search code examples
pythondjango-rest-frameworkdjango-channels

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


I want to change the API's behavior to JSON triggered (to call from the browser), but I'm not even able to call it from a Python client due to my limited knowledge about Python.

Can someone please help me with how to do like the manual shows? Here is my simple client:

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)    

Solution

  • I feel the docs is a bit unclear, this is the solution, made pr as well.

    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)
    

    From then the websocket will push model change to client