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

Django如何查询外键关联的已登录用户在另一张表中的对应数据

解决方案

你当前的代码存在两处逻辑问题:

  1. 过滤条件错误,没有关联当前登录的用户,反而指定了查询phone字段值为字符串'phone'的记录
  2. filter()方法返回的是查询结果集,需要取到对应实例后才能读取phone属性值

修改后的view.py代码:

def showform(request):
    form = FormNumber()
    phone = None
    if request.user.is_authenticated:
        # 以当前登录用户为条件过滤customer表
        user_customer = customer.objects.filter(user=request.user).first()
        # 确保存在对应记录再取phone,避免属性报错
        if user_customer:
            phone = user_customer.phone
            print(phone)
    # 若需要在模板中使用phone字段,可存入context传入
    context = {'form': form, 'phone': phone}
    return render(request, 'mpesa/pay.html', context)

额外优化建议:

  • 如果业务逻辑能保证每个登录用户在customer表中有且仅有一条对应记录,可以改用get方法查询,注意添加异常捕获即可:
    from django.core.exceptions import ObjectDoesNotExist
    # ...其他代码
    try:
        user_customer = customer.objects.get(user=request.user)
        phone = user_customer.phone
    except ObjectDoesNotExist:
        phone = None
    
  • 遵循Django模型命名规范,建议将customer类名改为首字母大写的Customer,可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 16:39:03