Django channels realtime total notification
Мне нужно общее количество уведомлений в реальном времени, используя каналы django.
signals.py
@receiver(post_save, sender=Notification)
def create_notification(sender, instance, created, **kwargs):
if created:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
'realtime_order',
{
'type': 'notification_count',
'text': Notification.objects.all().count()
}
)
consumers.py
class NotificationConsumer(WebsocketConsumer):
def __init__(self, *args, **kwargs):
super().__init__(args, kwargs)
self.room_group_name = None
def connect(self):
self.room_group_name = f'realtime_order'
self.accept()
# join the room group
async_to_sync(self.channel_layer.group_add)(
self.room_group_name,
self.channel_name,
)
def disconnect(self, close_code):
async_to_sync(self.channel_layer.group_discard)(
self.room_group_name,
self.channel_name,
)
def receive(self, text_data=None, bytes_data=None):
async_to_sync(self.channel_layer.group_send)(
self.room_group_name,
{
'type': 'notification_count',
'message': Notification.objects.all().count(),
}
)
def notification_count(self, event):
self.send(text_data=json.dumps(event))
Не знаю, правильная ли это процедура. И код не работает.