Django 通道中的异步等待无法获取具有 ID 的对象

Async await in django channels cannot get object with id

我的consumers.py:

    async def user_taskcompleted(self, event):
     me = User.objects.get(username=event['username'])

     print("ME",me)
     mentor=me.mentor
     print("MY MENTOR", mentor)
     id_task =event['task']
     print("GETTING ID",id_task)
     notification = event['username'] + ' Completed new Task ' + 
     event['title']
     print("notification", notification)

     task = await Task.objects.get(id=id_task)


     obj =  
     await self.create_notification_to_trainer(me,notification,task)
     obj.receiver.add(mentor)
     await self.send_json(event)
     print("Got message {} at {}".format(event, self.channel_name))


  @database_sync_to_async
  def create_notification_to_trainer(self, sender,notification,task):

    return Notification.objects.create(sender=sender 
    ,notification=notification,task=task)

我的signals.py:

@receiver(post_save, sender=Task)
def create_task_notification(sender, instance, created, **kwargs):
if  Task.objects.filter
(student=instance.student,student__mentor__isnull=False).exists():
if created:
    channel_layer = get_channel_layer()
    async_to_sync(channel_layer.group_send)(
        "gossip", {"type": "user.taskcompleted",
                   "event": "New Task",
                   "task": instance.id,
                   "username": instance.student.username,

                   "title": instance.title,
                   "mentor": instance.student.mentor.username

                   })

          print("TASK  ID",instance.id)
  else:
      print("NO TRAINER")

我正在尝试将数据保存到我的 consumers.py 中的模型以保存关于任务的通知 save.The 问题是我无法使用我的 [=] 中的任务 ID 获取任务25=]。它显示任务匹配查询在我的终端中不存在。

所有其他字段的打印语句显示在我的终端中,我也能够获得返回的正确任务 ID

如我的终端所示:

    TASK  ID 323
    ME mohitharshan123 
    MY MENTOR rohitharshan
    GETTING ID 323
    notification mohitharshan123 Completed new Task safasfa 

错误显示在 Task.objects.get(id=id_task)

如果您的 运行 在 async 方法中,您需要将 ORM 数据库调用包装在 await database_sync_to_async

from channels.db import database_sync_to_async

async def user_taskcompleted(self, event):
     me = await database_sync_to_async(User.objects.get)(username=event['username'])
     ...

查看有关此 here

的完整文档

P.S如果你有兴趣观察模型实例,看看Django Channels Rest Framework[免责声明我是主要贡献者的作者]

使用 asyncio.sleep 解决了问题

import asyncio
from channels.db import database_sync_to_async

async def hub_notify(self, event):
   asyncio.sleep(1)
   me = await database_sync_to_async(HubNotify.objects.get) 
   (username=event['username'])