python - 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)
解决方案
如果您在一个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我是主要贡献者的作者]
推荐阅读
- mysql - 多个 ORDER BY
- karate - 空手道不能断言 XML 响应包含 XPath
- three.js - Three.js OrbitControls 平移和场景旋转
- sql-server - SQL Server 上的快速并行插入性能(身份或唯一标识符)
- python - 不使用 itertools 的不重复排列
- mac-catalyst - Mac Catalyst ITMS-4241 错误上传二进制文件
- qml - 在 QML 中的信号处理程序中使用转换属性时,“预期的标记 ','”
- c# - 使用 ngrok 在 Teams 中测试机器人功能
- kubernetes - 如何防止 pod 在同一个命名空间中挂载秘密?
- reactjs - 如何在 React JS 中管理布局和对齐?