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()
views.py:
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)
try:
insert.save()
resp['status'] = 'success'
except Exception as ex:
resp['status'] = 'failed'
resp['mesg'] = ex
else:
resp['status'] = 'failed'
return HttpResponse(json.dumps(resp), content_type="application/json")
models.py:
class chatMessages(models.Model):
user_from = models.ForeignKey(User,
on_delete=models.CASCADE,related_name="sent")
user_to = models.ForeignKey(User,
on_delete=models.CASCADE,related_name="received")
message = models.TextField()
date_created = models.DateTimeField(default=timezone.now)
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: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#values
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: https://docs.djangoproject.com/en/4.1/ref/models/querysets/#values-list