How to display the user id in django

I have a function in which I have to, among other things, pass to the template the ids of the users who conducted the correspondence, but I get an error in the line:

pk_list = messages.values('user_from__pk').distinct()

def send_chat(request):
resp = {}
User = get_user_model()
if request.method == 'POST':
    post =request.POST
    u_from = UserModel.objects.get(id=post['user_from'])
    u_to = UserModel.objects.get(id=post['user_to'])
    messages = request.user.received.all()
    pk_list = messages.values('user_from__pk').distinct()
    correspondents = get_user_model().objects.filter(pk__in=list(pk_list))
    insert = chatMessages(user_from=u_from,user_to=u_to,message=post['message'],correspondents=correspondents)
        resp['status'] = 'success'
    except Exception as ex:
        resp['status'] = 'failed'
        resp['mesg'] = ex
    resp['status'] = 'failed'

return HttpResponse(json.dumps(resp), content_type="application/json")

class chatMessages(models.Model):
user_from = models.ForeignKey(User,
user_to = models.ForeignKey(User,
message = models.TextField()
date_created = models.DateTimeField(
correspondents = models.ForeignKey(User,
    on_delete=models.CASCADE,related_name="correspondents", null=True)

def __str__(self):
    return self.message

Error: TypeError: Field 'id' expected a number but got {'user_from__pk': 1}.

how can I fix this error?

problem is here:

pk_list = messages.values('user_from__pk').distinct()

queryset.values give you a list of dictionaries. in your case [{'user_from__pk': pk1}, {'user_from__pk': pk2},... e.t.c.]

more here:

And you need values_list.

pk_list = messages.values_list('user_from__pk', flat=True).distinct()

To avoid joins - you can do:

pk_list = messages.values_list('user_from_pk', flat=True).distinct()

more here:

Back to Top