Django官方教程中Python Shell导入Models无反馈问题求助
问题说明与解决步骤
首先明确:在Python Shell中执行from polls.models import Question,Choice无任何反馈是正常现象——Python在模块导入成功时默认不会输出任何内容,教程中提到的“显示数据库相关信息”指的是后续执行模型实例操作(创建、查询等)时的反馈,而非导入步骤本身。
验证模型是否正常工作
直接执行以下操作确认:
- 创建Question实例并保存:
from django.utils import timezone q = Question(question_text="What's new?", pub_date=timezone.now()) q.save() - 查询所有Question数据:
此时会输出类似Question.objects.all()<QuerySet [<Question: Question object (1)>]>的内容,说明模型与数据库连接正常。
若后续操作报错,排查以下点
- 确认
settings.py的INSTALLED_APPS中已正确添加应用配置:'polls.apps.PollsConfig'(或简写'polls') - 重新执行迁移命令确保生效:
python manage.py makemigrations python manage.py migrate - 检查
polls/models.py中的模型类是否正确继承models.Model,示例结构如下:from django.db import models class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
内容的提问来源于stack exchange,提问作者Suleyman Eminbeyli
相关产品推荐
相关产品推荐

