You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django膳食追踪网站访问模型查询数据库报错求助

问题描述

我正在开发基于Django、Python、SQL的膳食追踪网站,用MacBook Pro在VS Code终端运行测试文件时,访问模型做数据库查询报错:

django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

测试代码:

from models import Food_Table
food_names = Food_Table.objects.all('food_name', flat=True)
print(food_names)

模型代码:

class Food_Table(models.Model): 
    food_ID = models.AutoField(primary_key = True) 
    food_name = models.CharField(max_length = 40) 
    food_description = models.CharField(max_length = 1000)

完整报错栈:

/opt/anaconda3 /bin/python /Desktop/dietary_app/tests.py

Traceback (most recent call last): 
  File "/Desktop/dietary_app/tests.py", line 1, in <module>
    from models import Food_Table
  File "/Desktop/dietary_app/models.py", line 4, in <module>
    class Participant(models.Model): 
  File "/opt/anaconda3/lib/python3.9/site-packages/django/db/models/base.py", line 129, in __new__
     app_config = apps.get_containing_app_config(module)
  File "/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
     self.check_apps_ready()
  File "/opt/anaconda3/lib/python3.9/site-packages/django/apps/registry.py", line 137, in check_apps_ready
     settings.INSTALLED_APPS
  File "/opt/anaconda3/lib/python3.9/site-packages/django/conf/__init__.py", line 102, in __getattr__
     self._setup(name)
  File "/opt/anaconda3/lib/python3.9/site-packages/django/conf/__init__.py", line 82, in _setup
    raise ImproperlyConfigured( 
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

解决方法

方法1:手动初始化Django环境到测试文件

直接运行独立py文件访问Django模型时,必须先加载Django配置。修改测试文件如下:

import django
import os

# 替换为你的项目settings路径,比如项目根目录下的settings.py
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dietary_app.settings')
django.setup()

# 初始化完成后再导入模型
from models import Food_Table
# 注意:all()方法不接受字段参数,获取指定字段用values_list
food_names = Food_Table.objects.values_list('food_name', flat=True)
print(food_names)

方法2:使用Django自带Shell(推荐)

用Django内置shell会自动加载配置,无需手动初始化:

  1. 终端进入项目根目录
  2. 执行命令:
python manage.py shell
  1. 在shell中执行查询:
from models import Food_Table
food_names = Food_Table.objects.values_list('food_name', flat=True)
print(food_names)

额外检查项

  • 确保你的app已添加到项目settings.py的INSTALLED_APPS:
INSTALLED_APPS = [
    # 其他默认应用
    'dietary_app',
]
  • 确认模型迁移已执行:
python manage.py makemigrations
python manage.py migrate

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 12:30:12