Django如何查询外键关联的已登录用户在另一张表中的对应数据
解决方案
你当前的代码存在两处逻辑问题:
- 过滤条件错误,没有关联当前登录的用户,反而指定了查询
phone字段值为字符串'phone'的记录 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
相关产品推荐
相关产品推荐

