django:在websocket上更新模型值

问题描述

所以我将用户模型扩展到此

class ProfileImage(models.Model):
    """
    Profile model
    """
    user = models.OneToOneField(
        verbose_name=_('User'),#to=settings.AUTH_USER_MODEL,to = User,related_name='profile',on_delete=models.CASCADE
    )
    avatar = models.ImageField(upload_to='profile_image')
    notifications = models.FloatField(default='0')

通知值是0,但是我想要的是在收到网络套接字时给通知+1,那么当收到消息时我该怎么做?这是我的消费者。py

class ChatConsumer(AsyncConsumer):
    async def websocket_connect(self,event):
        print("connected",event)

        other_user = self.scope['url_route']['kwargs']['username']
        me = self.scope['user']
        # print(other_user,me)
        thread_obj = await self.get_thread(me,other_user)
        self.thread_obj = thread_obj
        chat_room = f"thread_{thread_obj.id}"
        self.chat_room = chat_room
        await self.channel_layer.group_add(
            chat_room,self.channel_name
        )

        await self.send({
            "type": "websocket.accept"
        })
        # await asyncio.sleep(10)

    async def websocket_receive(self,event):
        # when a message is received from the websocket
        print("receive",event)

        front_text = event.get('text',None)
        if front_text is not None:
            loaded_dict_data = json.loads(front_text)
            msg =  loaded_dict_data.get('message')
            user = self.scope['user']
            username = 'default'
            if user.is_authenticated:
                username = user.username
            myResponse = {
                'message': msg,'username': username,}

            await self.create_chat_message(user,msg)

            # broadcast the message event to be send
            await self.channel_layer.group_send(
                self.chat_room,{
                    "type": "chat_message","text": json.dumps(myResponse)
                }
            )

    async def chat_message(self,event):
        # sends the actual message
        await self.send({
            "type": "websocket.send","text": event['text']
        })

    async def websocket_disconnect(self,event):
        # when the socket connects
        print("disconnected",event)

    @database_sync_to_async
    def get_thread(self,user,other_username):
        return Thread.objects.get_or_new(user,other_username)[0]

    @database_sync_to_async
    def create_chat_message(self,me,msg):
        thread_obj = self.thread_obj
        return ChatMessage.objects.create(thread=thread_obj,user=me,message=msg)

我该怎么做?,我认为可以通过websocket接收来完成,但是我尝试并且不能,谢谢您的帮助

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)