You need to enable JavaScript to run this app. Django展示PostgreSQL表内容仅显示表头无数据的问题及解决方法
优惠活动
大模型
产品
解决方案
定价
更多

Django展示PostgreSQL表内容仅显示表头无数据的问题及解决方法

Django读取PostgreSQL表仅展示表头无数据问题修复

问题现象

在Django中通过ListView展示PostgreSQL存储的业务数据时,页面仅渲染表格表头,无任何数据加载也无报错信息,通过pgAdmin核验目标表中存在大量有效数据。

原实现代码

models.py

from django.db import models
from datetime import datetime

# Create your models here.

class SensorData(models.Model):
    device_name = models.TextField()
    sensor_type = models.TextField()
    sensor_data = models.SmallIntegerField()
    sensor_date = models.DateTimeField()
    
    def __str__(self):
        return self.device_name

views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView
from .models import SensorData

# Create your views here.

class ErrorView(ListView):
    model = SensorData
    template_name = 'errors.html'

urls.py

from django.urls import path
from .views import ErrorView

urlpatterns = [
    path('errors/', ErrorView.as_view(), name='errors'),
    path('', ErrorView.as_view(), name='errors'),
]

模板文件 errors.html

{% extends 'layout.html' %}
{%block content %}

<section class ='infoContainer'>
    <div id = 'sensorInfo'>
        <h2> Error Information </h2>
        <table id = "deviceTable">
            <tr>
                <th><strong>Device </strong></th>
                <th><strong>Sensor Type </strong></th>
                <th><strong>Date</strong></th>
                <th><strong>Information</strong></th>
            </tr>

            {% for error in object_list %}
                
            <tr>     
                <td> {{error.device_name}} </td>
                <td> {{error.sensor_type}} </td>
                <td> {{error.sensor_date}} </td>
                <td> {{error.sensor_data}} </td>
            </tr>
            
            {% endfor %}
        </table>
    </div>
</section>
{% endblock content %}

修复方案

问题根因为Django默认会将模型所属的应用文件夹名称作为表名前缀,拼接生成查询的表名,与PostgreSQL中实际存在的表名不匹配,导致查询无结果。
只需在SensorData模型中添加Meta类,指定关联的实际表名即可:

class SensorData(models.Model):
    device_name = models.TextField()
    sensor_type = models.TextField()
    sensor_data = models.SmallIntegerField()
    sensor_date = models.DateTimeField()
    
    # 新增Meta类指定表信息
    class Meta:
        managed = False # 告知Django不需要对该表执行表结构创建、修改等迁移操作
        db_table = 'tablename' # 将tablename替换为PostgreSQL中实际的表名
    
    def __str__(self):
        return self.device_name

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 21:45:10