You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django中如何传递user_from id至参数?解决NameError问题

问题解决方法

核心错误修复

你碰到的NameError是因为Django ORM的values()方法需要传入字符串形式的字段名,直接写user_from__pk会被Python当成未定义的变量。把字段名改成字符串即可:

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

额外问题修正

除了这个错误,代码还有几个潜在问题需要处理:

  • UserModel未定义:你已经用User = get_user_model()获取了用户模型,后续的UserModel要替换成User:
    u_from = User.objects.get(id=post['user_from'])
    u_to = User.objects.get(id=post['user_to'])
    
  • correspondents字段类型不匹配:chatMessages模型里的correspondents是ForeignKey(对应单个用户实例),但你现在传的是QuerySet(多个用户),会导致保存失败。需根据业务逻辑传入单个用户,比如对话的接收方u_to:
    insert = chatMessages(user_from=u_from, user_to=u_to, message=post['message'], correspondents=u_to)
    
  • pk_list格式优化:values('user_from__pk')返回字典列表(如[{'user_from__pk': 1}, ...]),直接传给pk__in会出错。改用values_list加flat=True能直接得到纯pk值的列表:
    pk_list = messages.values_list('user_from__pk', flat=True).distinct()
    correspondents = User.objects.filter(pk__in=pk_list)
    

修正后的完整views.py代码

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

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

内容的提问来源于stack exchange,提问作者Xrystik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:03:33