Issue
I have a code where I need to pass the user_from id (the user from whom the message comes), but when I write user_from__pk
writes an error that there is no such name
NameError: name 'user_from__pk' is not defined
My code:
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
how can I pass the user_from id in the line:
pk_list = messages.values(user_from__pk).distinct()
Solution
.values()
method accepts field names as string. So, it should be .values("user_from__pk")
Answered By - JPG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.