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

Viewed 602

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)    
2 Answers

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

I do not receive anything on changes when I do that. I connect successfully to the route but when I modify a product I do not get any messages from the server to the client.

This is my consumer :

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)
Related