pythondjangojsonresponse

Issue with django json response


I have issue with json response. messages.values() gives me user_id instead of username. How to get username?

Here is my code:

class LivechatMessage(models.Model):
    user=models.ForeignKey(User,on_delete=models.CASCADE, null=True)


def getMessages(request):
    messages =LivechatMessage.objects.all()
    return JsonResponse({"messages":list(messages.values())})

Solution

  • You can do like this to access related attributes

    def getMessages(request):
        messages =LivechatMessage.objects.all()
        return JsonResponse({"messages":list(messages.values('user__username','user__id'))})