我的消费者。py:
Content
我的信号。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)
我正在尝试将数据保存到我的consumers.py中的模型中以在保存任务时保存通知。问题是我无法使用我的consumers.py中的任务ID来获取任务。它显示了任务匹配查询在我的终端机中不存在。
我的终端中显示了所有其他字段的打印语句,即时消息还能够获取返回的正确任务ID
如我的终端所示:
@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")
该错误显示在Task.objects.get(id = id_task)
答案 0 :(得分:1)
如果您在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'])
...
查看关于此here
的完整文档 P.S如果您有兴趣观察Model实例,请查看Django Channels Rest Framework
[Disclamer我是主要贡献者的作者]
答案 1 :(得分:0)
使用asyncio.sleep解决了该问题
ret = f'Done! {deleted} entr{deleted != 1 and "ies were" or "y was"} removed.'