在Django项目中,我想实现一个简单的聊天框。
版本
Django版本3.0.8
Models.py
class DirectMessageClass(models.Model):
sender = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='from_this')
receiver = models.ForeignKey(User, on_delete=models.CASCADE,
related_name='to_this')
timestamp = models.DateTimeField(auto_now=True)
content = models.CharField(max_length=200)
read = models.BooleanField(default=False)
def serialize(self):
return {
"id": self.id,
"sender": self.sender.username,
"sendername":self.sender.profile.firstname,
"senderimage":self.sender.profile.image.url,
"receiver": self.receiver.username,
"content": self.content,
"timestamp":self.timestamp.strftime("%m/%d/%Y, %H:%M:%S"), # to format date
"read":self.read,
}
Views.py
def loadbox(request):
user = request.user
# Return messages in reverse chronologial order
messages = DirectMessageClass.objects.filter(receiver=user).order_by("-timestamp").all()
return JsonResponse([message.serialize() for message in messages], safe=False)
我成功获取了消息,并使用此方法将其转换为/ loadbox路径中的JSON对象。稍后,我获取此数据以显示消息,并且可以正常工作。
我的/ loadbox路径示例
[{"id": 1, "sender": "ekvatorcizgisi", "sendername": "Asli",
"receiver": "bilge", "content": "hi", "timestamp": "09/02/2020, 08:22:26", "read": true}]
但是,因为我希望它显示为对话框。我还需要在此JSON对象中添加回复消息。
在views.py中,我尝试
def loadbox(request):
user = request.user
# Return messages in reverse chronologial order
messages = DirectMessageClass.objects.filter(receiver=user).order_by("-timestamp").all()
# return replies sent by the current user
replies = DirectMessageClass.objects.filter(sender=user).order_by("-timestamp").all()
return JsonResponse([message.serialize() for message in messages], safe=False)
我不确定如何在/ loadbox路径中返回多个Json响应
return JsonResponse([message.serialize() for message in messages,reply.serialize() for reply in replies], safe=False)
显然出现语法错误,(SyntaxError:无效语法)我也尝试将其全部放入列表中,但无法使其正常工作。
我的理想输出是
[messages: {"id": 1, "sender": "ekvatorcizgisi", "sendername": "Asli",
"receiver": "bilge", "content": "hi", "timestamp": "09/02/2020, 08:22:26", "read": true}
replies:{"id": 3, "sender": "bilged", "sendername": "bilge",
"receiver": "Asli", "content": "hi there", "timestamp": "09/02/2020, 08:22:26", "read": false}]
也许我会为答复邮件提供另一条路径来解决此问题,但我想知道还有更好的方法吗?
答案 0 :(得分:2)
使用 列出上层包装 技术
def loadbox(request):
# rest of your code
return JsonResponse(
[
*[message.serialize() for message in messages],
*[reply.serialize() for reply in replies]
],
safe=False
)
简单演示:
In [1]: foo = [1,2,3]
In [2]: bar = [5,6,7]
In [3]: foo_bar = [*foo,*bar]
In [4]: foo_bar
Out[4]: [1, 2, 3, 5, 6, 7]