Django关联模型获取Field Id报错:期望数字却得到字符串
问题解决:Field 'id' expected a number but got 'GANDE1'
问题根源
你在update_customer_profile视图里犯了核心错误:Profile的customer字段是和User模型的一对一关联,查询时你传入了customer_user.username(字符串类型,比如'GANDE1'),但Django会默认用这个值去匹配User的主键id(数字类型),因此触发了类型不匹配的报错。
修复代码
直接使用已获取的customer_user对象查询Profile即可,一对一关联字段支持直接接收关联模型的实例:
def update_customer_profile(request, pk): # 获取登录用户 user = request.user # 检查登录用户是否为staff(原代码未完成,建议补充逻辑) try: customer_user = User.objects.get(id=pk) except User.DoesNotExist: return redirect('user-register') else: count_users = User.objects.count() # 用User对象查询关联的Profile,而非username字符串 user_profile = Profile.objects.get(customer=customer_user) # 后续可添加表单处理逻辑,例如: # form = ProfileUpdateForm(instance=user_profile) # return render(request, 'update_profile.html', {'form': form})
额外优化建议
利用一对一反向查询简化代码:
因为注册时通过信号自动创建了Profile,你可以直接通过User对象反向获取关联的Profile,省去额外查询:# 替换原查询行 user_profile = customer_user.profile修复搜索视图的潜在问题:
create_account视图中,Q(customer__exact = value)会匹配User的主键,若想通过用户名搜索,需修改为:user_filter = Q(customer__username__exact=value) | Q(account_number__exact=value)优化模板变量命名:
模板循环变量customer对应Account对象,customer.customer指代关联的User,命名易混淆,建议将循环变量改为account,模板中改为account.customer.profile,可读性更强。
内容的提问来源于stack exchange,提问作者apollos
相关产品推荐
相关产品推荐

