I tried this approach stackoverflow but it didn't work
consumer.py
import json
import asyncio
from channels.consumer import AsyncConsumer
from django.contrib.auth import get_user_model
from channels.db import database_sync_to_async
from .models import Analytics
class AnalyticsConsumer(AsyncConsumer):
async def websocket_connect(self, event):
print('connected', event)
await self.send({
'type': 'websocket.accept'
})
analytics_obj = await self.getAnalytics()
await self.send({
'type': 'websocket.send',
'text': str(analytics_obj)
})
async def websocket_receive(self, event):
print('receive', event)
async def websocket_disconnect(self, event):
print('disconnected', event)
@database_sync_to_async
def getAnalytics(self):
return list(Analytics.objects.all().values())[0]['number']
The console displays the message == analytics_obj
but when I make changes in the database, it doesn't reflect in the console message. For that, I need to refresh the browser. What is the point in refreshing the browser when you are using WebSocket.
Just by updating a value in the db no new message is being sent to frontend. You need to send an "update" message over django channels after updating the database. So far the only time you send the analytics data is when you connect to the server.