Django模型生成的PostgreSQL表无法通过PgAdmin及SQL查询的原因排查
问题分析与解决
核心问题
执行原生SQL或PgAdmin查询时出现relation "machine_projects" does not exist错误,根源在于三点:
- PostgreSQL大小写规则:未加双引号的标识符(表名、字段名)会被自动转为小写,你写的首字母大写名称与数据库实际存储的不匹配;
- Django表名生成规则:默认表名为
[app标签小写]_[模型名小写],而非你使用的Machine_projects; - 模型与迁移不同步:
models.py包含First_Name和Last_Name字段,但迁移文件里没有这两个字段,导致数据库表结构和模型不一致。
解决步骤
1. 确认真实表名
通过Django Shell查看Projects模型对应的数据库表名:
python manage.py shell
在Shell中执行:
from machine.models import Projects print(Projects._meta.db_table)
输出结果即为数据库中实际存在的表名(通常是全小写的machine_projects)。
2. 修正原生SQL语句
将views.py中的SQL语句改为匹配真实表名和字段名(全小写):
cursor.execute("SELECT no_of_projects FROM machine_projects WHERE first_name = %s", [row[0]])
注意:Django会自动将模型中的驼峰字段名(如First_Name)转为下划线小写格式(first_name)存储在数据库中。
3. 同步模型与迁移文件
由于你的模型和迁移文件字段不一致,需重新生成并执行迁移:
# 生成新的迁移文件 python manage.py makemigrations # 同步数据库 python manage.py migrate
若旧迁移存在异常,可回退重置后重新操作:
# 回退该app的所有迁移 python manage.py migrate machine zero # 删除旧迁移文件(保留migrations目录下的__init__.py) rm machine/migrations/0001_initial.py # 重新生成并执行迁移 python manage.py makemigrations machine python manage.py migrate machine
4. 验证查询
修改后重启项目,或在PgAdmin中使用正确的全小写名称查询:
SELECT no_of_projects FROM machine_projects WHERE first_name = '目标用户名';
附:修正后的views.py关键片段
def test2(request): user = User.objects.get(username=request.user.username) if user.is_authenticated: print(user) with connection.cursor() as cursor: cursor.execute("SELECT first_name FROM auth_user WHERE username = %s", [user.username]) row = cursor.fetchone() print(row[0]) # 修正表名与字段名 cursor.execute("SELECT no_of_projects FROM machine_projects WHERE first_name = %s", [row[0]]) row2 = cursor.fetchone() pro = Projects.objects.get(pk=2) print(pro, row2[0]) all_tables = connection.introspection.table_names() print(all_tables) return redirect('register2') else: return render(request, 'test2.html')
内容的提问来源于stack exchange,提问作者Houston Khanyile
相关产品推荐
相关产品推荐

