Django使用原生SQL查询引用auth_user表提示不存在auth_user.id列问题
报错原因
你在自定义SQL中给auth_user表指定了别名resztvevok,后续引用该表字段时必须使用别名,不能再用原表名auth_user,因此触发了no such column: auth_user.id的报错。
另外使用Profile.objects.raw()查询时,必须返回Profile表的主键id,否则Django无法正确映射生成模型实例。
方案1:修正raw查询写法
resztvevok = Profile.objects.raw(''' SELECT stressz_profile.id, auth_user.last_name, auth_user.first_name, stressz_profile.projekt_id FROM auth_user INNER JOIN stressz_profile ON stressz_profile.user_id = auth_user.id WHERE stressz_profile.projekt_id = 1 ''')
方案2:更推荐的Django原生ORM写法(无需手动写SQL)
利用Django ORM的跨表关联特性,直接通过双下划线和select_related实现连表查询,自动规避SQL语法错误、SQL注入风险:
# select_related会自动执行INNER JOIN关联User表 resztvevok = Profile.objects.filter(projekt_id=1).select_related('user') # 取值示例 for profile in resztvevok: # 直接通过关联字段取auth_user表的信息 print(profile.user.last_name, profile.user.first_name, profile.projekt_id)
内容的提问来源于stack exchange,提问作者RlM
相关产品推荐
相关产品推荐

