Ampare1987 2021-12-10 09:16 采纳率: 55.6%
浏览 53
已结题

Django初学者在做官网Models说明书时遇到的问题想大家请教

问题遇到的现象和发生背景

我在学习Django,我之前没接触过数据库,现在刚刚开始学,目前再看Django说明书的Models部分,我看到的网页如下:
https://docs.djangoproject.com/en/4.0/topics/db/models/

问题相关代码,请勿粘贴截图

按照说明我在Models中加入了如下数据库

from django.db import models

class Person(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=60)
    shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES)

在cmd中运行

py manage.py shell
from polls.models import Person
p =Person(name="Julian",shirt_size="S")
p.save()
运行结果及报错内容

可是却出现一大堆的错误

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py in _execute(self, sql, params, *ignored_wrapper_args)
     83             else:
---> 84                 return self.cursor.execute(sql, params)
     85

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py in execute(self, query, params)
    422         query = self.convert_query(query)
--> 423         return Database.Cursor.execute(self, query, params)
    424

OperationalError: table polls_person has no column named name

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
<ipython-input-3-e403c3dbfc7c> in <module>
----> 1 p.save()

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py in save(self, force_insert, force_update, using, update_fields)
    724                 update_fields = frozenset(loaded_fields)
    725
--> 726         self.save_base(using=using, force_insert=force_insert,
    727                        force_update=force_update, update_fields=update_fields)
    728     save.alters_data = True

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py in save_base(self, raw, force_insert, force_update, using, update_fields)
    761             if not raw:
    762                 parent_inserted = self._save_parents(cls, using, update_fields)
--> 763             updated = self._save_table(
    764                 raw, cls, force_insert or parent_inserted,
    765                 force_update, using, update_fields,

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py in _save_table(self, raw, cls, force_insert, force_update, using, update_fields)
    866
    867             returning_fields = meta.db_returning_fields
--> 868             results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
    869             if results:
    870                 for value, field in zip(results[0], returning_fields):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py in _do_insert(self, manager, using, fields, returning_fields, raw)
    904         return the newly created data for the model.
    905         """
--> 906         return manager._insert(
    907             [self], fields=fields, returning_fields=returning_fields,
    908             using=using, raw=raw,

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py in manager_method(self, *args, **kwargs)
     83         def create_method(name, method):
     84             def manager_method(self, *args, **kwargs):
---> 85                 return getattr(self.get_queryset(), name)(*args, **kwargs)
     86             manager_method.__name__ = method.__name__
     87             manager_method.__doc__ = method.__doc__

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py in _insert(self, objs, fields, returning_fields, raw, using, ignore_conflicts)
   1268         query = sql.InsertQuery(self.model, ignore_conflicts=ignore_conflicts)
   1269         query.insert_values(fields, objs, raw=raw)
-> 1270         return query.get_compiler(using=using).execute_sql(returning_fields)
   1271     _insert.alters_data = True
   1272     _insert.queryset_only = False

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\compiler.py in execute_sql(self, returning_fields)
   1414         with self.connection.cursor() as cursor:
   1415             for sql, params in self.as_sql():
-> 1416                 cursor.execute(sql, params)
   1417             if not self.returning_fields:
   1418                 return []

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py in execute(self, sql, params)
     96     def execute(self, sql, params=None):
     97         with self.debug_sql(sql, params, use_last_executed_query=True):
---> 98             return super().execute(sql, params)
     99
    100     def executemany(self, sql, param_list):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py in execute(self, sql, params)
     64
     65     def execute(self, sql, params=None):
---> 66         return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
     67
     68     def executemany(self, sql, param_list):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py in _execute_with_wrappers(self, sql, params, many, executor)
     73         for wrapper in reversed(self.db.execute_wrappers):
     74             executor = functools.partial(wrapper, executor)
---> 75         return executor(sql, params, many, context)
     76
     77     def _execute(self, sql, params, *ignored_wrapper_args):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py in _execute(self, sql, params, *ignored_wrapper_args)
     82                 return self.cursor.execute(sql)
     83             else:
---> 84                 return self.cursor.execute(sql, params)
     85
     86     def _executemany(self, sql, param_list, *ignored_wrapper_args):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\utils.py in __exit__(self, exc_type, exc_value, traceback)
     88                 if dj_exc_type not in (DataError, IntegrityError):
     89                     self.wrapper.errors_occurred = True
---> 90                 raise dj_exc_value.with_traceback(traceback) from exc_value
     91
     92     def __call__(self, func):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\utils.py in _execute(self, sql, params, *ignored_wrapper_args)
     82                 return self.cursor.execute(sql)
     83             else:
---> 84                 return self.cursor.execute(sql, params)
     85
     86     def _executemany(self, sql, param_list, *ignored_wrapper_args):

~\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py in execute(self, query, params)
    421             return Database.Cursor.execute(self, query)
    422         query = self.convert_query(query)
--> 423         return Database.Cursor.execute(self, query, params)
    424
    425     def executemany(self, query, param_list):

OperationalError: table polls_person has no column named name
我的解答思路和尝试过的方法

我尝试过 manage.py migrate和 manage.py makemigrations,但好像都不管用。

  • 写回答

5条回答 默认 最新

  • 关注
    获得0.30元问题酬金

    你使用的什么数据库,mysql,还是其他,mysql先要下载pymysql,在项目settings.py统计目录下的init.py文件初始化mysql

    import pymysql
    
    pymysql.version_info = (1, 4, 6, 'final', 0)  # change mysqlclient version
    pymysql.install_as_MySQLdb()
    

    将settings.py文件内的DATABASES修改成如下

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': '你创建的数据库名',
            'USER': 'root',
            'PASSWORD': '你的数据库密码.',
            'HOST': '192.168.2.2',
            # 'HOST': '127.0.0.1',
            'PORT': '3306',
            'TEST': {
                'NAME': 'django_db_test'  # 用于单元测试的数据库
            }
    
        }
    }
    

    之后再调用

    python manage.py makemigrations
    
    python manage.py migrate
    

    有帮助请点击一下采纳,有问题评论交流

    img

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 12月18日
  • 创建了问题 12月10日

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)