首页 > 解决方案 > django 频道中的异步等待无法获取具有 id 的对象

问题描述

我的消费者.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)

我的信号.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中的模型以保存关于任务保存的通知。问题是我无法使用我的consumers.py中的任务ID获取任务。它显示任务匹配查询不存在于我的终端中。

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

如我的终端所示:

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

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

标签: pythondjangodjango-channels

解决方案


如果您在一个async方法中运行,您需要将您的 ORM DB 调用包装在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'])
     ...

在这里查看完整的文档

PS如果你有兴趣观察模型实例看看Django Channels Rest Framework[disclamer我是主要贡献者的作者]


推荐阅读