如何配置将 json 对象发送到 Django Channels?

How do I configure the sending of json objects to Django Channels?

如何配置将 json 对象发送到 Django Channels?确保在管理面板中添加新对象时,它立即实时显示在前面。也许有人有任何例子。将不胜感激。

有一个工厂对象:

models.py

class Factory(models.Model):

     OBJECT_CHOICES = (
            ('Завод', 'Завод'),
            ('Вышка', 'Вышка'),
            ('Хранилище', 'Хранилище'),
            ('АЗС', 'АЗС')
        )

    title = models.CharField(max_length=200)
    choice = models.CharField(max_length=15, choices=OBJECT_CHOICES, default = '')
    address = YmapCoord(max_length=200, start_query=u'Россия', size_width=500, size_height=500, unique = True)

当向/getFactory/发出GET请求时,发出JSON类型

[
   {
    "title": "factory",
    "choice": "Завод",
    "address": [
        55.744607932133505,
        48.99357300960071
    ]
   }
]

首先,您需要一个 consumer 并且您应该在那里定义 groups 字段。

A WebsocketConsumer’s channel will automatically be added to (on connect) and removed from (on disconnect) any groups whose names appear in the consumer’s groups class attribute.

那么您的前端应该以某种方式连接到消费者并监听更新。 完成后,您可以从项目的任何地方发送新消息。例如,来自 post_save 信号。

from channels import Group
from django.db.models import signals
from django.dispatch import receiver


@receiver(signals.post_save, sender=Factory)
def notify_group(sender, instance, **kwargs):
    if kwargs['created']:
        group_name = 'your group'
        Group(group_name).send({'text': 'message or object'})