• 【Django】4 Django模型


    每个模型是一个Python 类,集成django.db.models.Modle类

    该模型的每个属性表示一个数据库表字段

    通过API 自动生成数据库访问 .../sign/modles.py 文件,通过模型完成表创建。

     TypeError: ForeignKey.__init__() missing 1 required positional argument: 'on_delete'

    在创建一个新模型时 ,出现错误TypeError: ForeignKey.__init__() missing 1 required positional argument: ‘on_delete‘_爱吃龙虾的小黑的博客-CSDN博客

    1. E:\data\python\djaongo_prj\guest> python manage.py makeigrations sign
    2. Traceback (most recent call last):
    3. File "E:\data\python\djaongo_prj\guest\manage.py", line 21, in
    4. main()
    5. File "E:\data\python\djaongo_prj\guest\manage.py", line 17, in main
    6. execute_from_command_line(sys.argv)
    7. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    8. utility.execute()
    9. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\__init__.py", line 416, in execute
    10. django.setup()
    11. File "D:\software\python3\anconda3\Lib\site-packages\django\__init__.py", line 24, in setup
    12. apps.populate(settings.INSTALLED_APPS)
    13. File "D:\software\python3\anconda3\Lib\site-packages\django\apps\registry.py", line 116, in populate
    14. app_config.import_models()
    15. File "D:\software\python3\anconda3\Lib\site-packages\django\apps\config.py", line 269, in import_models
    16. self.models_module = import_module(models_module_name)
    17. File "D:\software\python3\python310\lib\importlib\__init__.py", line 126, in import_module
    18. return _bootstrap._gcd_import(name[level:], package, level)
    19. File "", line 1050, in _gcd_import
    20. File "", line 1027, in _find_and_load
    21. File "", line 1006, in _find_and_load_unlocked
    22. File "", line 688, in _load_unlocked
    23. File "", line 883, in exec_module
    24. File "", line 241, in _call_with_frames_removed
    25. File "E:\data\python\djaongo_prj\guest\sign\models.py", line 20, in
    26. class Guest(models.Model):
    27. File "E:\data\python\djaongo_prj\guest\sign\models.py", line 21, in Guest
    28. event = models.ForeignKey(Event) # 关联发布会id
    29. TypeError: ForeignKey.__init__() missing 1 required positional argument: 'on_delete'

     必须要设置级联删除,也就是当你删除一条信息时,会级联的删除所有和这一条信息对应的另一张表的多个信息,也就是指定on_delete=models.CASCADE

    event = models.ForeignKey(Event,on_delete=models.CASCADE)  # 关联发布会id

    1. # 嘉宾
    2. class Guest(models.Model):
    3. event = models.ForeignKey(Event,on_delete=models.CASCADE) # 关联发布会id
    4. realname = models.CharField(max_length=64) # 姓名
    5. phone = models.CharField(max_length=16) # 手机号
    6. email = models.EmailField() # 邮箱
    7. sign = models.BooleanField() # 签到状态
    8. create_time = models.DateTimeField(auto_now=True) # 创建时间(自动获取当前时间)
    9. class Meta:
    10. unique_together = ('phone', 'event')
    11. def __str__(self):
    12. return self.realname

     python manage.py makemigrations sign

    1. E:\data\python\djaongo_prj\guest> python manage.py makemigrations sign
    2. System check identified some issues:
    3. WARNINGS:
    4. sign.Event: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    5. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SignConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
    6. sign.Guest: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    7. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SignConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
    8. Migrations for 'sign':
    9. sign\migrations\0001_initial.py
    10. - Create model Event
    11. - Create model Guest

      python manage.py migrate

    1. E:\data\python\djaongo_prj\guest> python manage.py migrate
    2. System check identified some issues:
    3. WARNINGS:
    4. sign.Event: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    5. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SignConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
    6. sign.Guest: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
    7. HINT: Configure the DEFAULT_AUTO_FIELD setting or the SignConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
    8. Operations to perform:
    9. Apply all migrations: admin, auth, contenttypes, sessions, sign
    10. Running migrations:
    11. Applying auth.0012_alter_user_first_name_max_length... OK
    12. Applying sign.0001_initial... OK
    13. E:\data\python\djaongo_prj\guest>

    admin  后台 管理

    1. from django.contrib import admin
    2. # Register your models here.
    3. # admin 后台管理 创建的发布会和嘉宾表示同样可以通过Admin 后台管理
    4. from django.contrib import admin
    5. from sign.models import Event ,Guest
    6. # Register your models here.
    7. class EventAdmin(admin.ModelAdmin):
    8. list_display = ['name', 'status', 'start_time','id']
    9. search_fields = ['name'] # 搜索功能
    10. list_filter = ['status'] # 过滤器
    11. class GuestAdmin(admin.ModelAdmin):
    12. list_display = ['realname', 'phone','email','sign','create_time','event_id']
    13. list_display_links = ('realname', 'phone') # 显示链接
    14. search_fields = ['realname','phone'] # 搜索功能
    15. list_filter = ['sign'] # 过滤器
    16. admin.site.register(Event, EventAdmin)
    17. admin.site.register(Guest, GuestAdmin)

    1. Microsoft Windows [版本 10.0.19045.3448]
    2. (c) Microsoft Corporation。保留所有权利。
    3. E:\data\python\djaongo_prj\guest>python manage.py shell
    4. Python 3.10.0 (tags/v3.10.0:b494f59, Oct 4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)]
    5. Type 'copyright', 'credits' or 'license' for more information
    6. IPython 8.10.0 -- An enhanced Interactive Python. Type '?' for help.
    7. In [1]:
    8. In [1]:
    9. In [1]: from sign.models import Event,Guest
    10. In [2]: Event.objects.all()
    11. Out[2]: 5发布会>]>
    12. In [3]:

    from sign.models import Event,Guest  导入模块

     Event.objects.all()   所有对象

    配置 MySQL  

     pip  install pymysql

    数据库创建表

    报错 [Err] 1055 - Expression #1 of ORDER BY

    [Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'information_schema.PROFILING.SEQ' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

    [Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated_Ricardo · M · YUAN的博客-CSDN博客

     

    在配置文件的末尾加上这段代码:
    [mysqld]
    sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

     

    1. CREATE TABLE `sign_event` (
    2. `id` int NOT NULL AUTO_INCREMENT,
    3. `name` varchar(50) DEFAULT NULL COMMENT '名称',
    4. `limit` int DEFAULT NULL COMMENT 'limit',
    5. `status` varchar(1) DEFAULT '1' COMMENT '状态 0:隐藏 1:显示',
    6. `address` varchar(500) DEFAULT NULL COMMENT '地址',
    7. start_time DATE,
    8. create_time DATE,
    9. PRIMARY KEY (`id`)
    10. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统配置信息表';
    1. CREATE TABLE `sign_guest` (
    2. `event_id` int NOT NULL ,
    3. `realname` varchar(50) DEFAULT NULL COMMENT '名称',
    4. `phone` varchar(11) COMMENT '手机号',
    5. `email` varchar(50) ,
    6. `sign` VARCHAR(1) DEFAULT '1' COMMENT '状态 0:隐藏 1:显示',
    7. create_time DATE,
    8. PRIMARY KEY (`event_id`,`phone`)
    9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='嘉宾表';

    insert into  sign_guest(realname,phone,email,sign,event_id,create_time)values("tom","12344444","1111@qq.com",1,123456,now())


    select * from sign_guest

     

    1. from pymysql import cursors, connect
    2. # 连接数据库
    3. conn = connect(host='192.168.56.10', user='root', password='root',
    4. db='guest', charset='utf8mb4', cursorclass=cursors.DictCursor)
    5. try:
    6. with conn.cursor() as cursors:
    7. # 创建嘉宾数据
    8. sql = 'insert into sign_guest(realname,phone,email,sign,event_id,create_time)values("tom2","12344444","1111@qq.com",1,123456,now())'
    9. cursors.execute(sql)
    10. conn.commit()
    11. with conn.cursor() as cursor:
    12. # 查询
    13. sql = "select * from sign_guest where phone=%s"
    14. cursor.execute(sql, ('12344444',))
    15. res = cursor.fetchone()
    16. print(res)
    17. finally:
    18. conn.close()

     

     Django 连接 mysql 

    1. DATABASES = {
    2. 'default': {
    3. 'ENGINE': 'django.db.backends.sqlite3',
    4. 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    5. }
    6. }

     

     

     

    1. import pymysql
    2. pymysql.install_as_MySQLdb()
    3. """
    4. 如果你使用pymysql驱动的话,上面两行必须添加。
    5. """

     

    1. E:\data\python\djaongo_prj\guest> python manage.py migrate
    2. Traceback (most recent call last):
    3. File "E:\data\python\djaongo_prj\guest\manage.py", line 21, in
    4. main()
    5. File "E:\data\python\djaongo_prj\guest\manage.py", line 17, in main
    6. execute_from_command_line(sys.argv)
    7. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line
    8. utility.execute()
    9. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\__init__.py", line 436, in execute
    10. self.fetch_command(subcommand).run_from_argv(self.argv)
    11. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\base.py", line 412, in run_from_argv
    12. self.execute(*args, **cmd_options)
    13. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\base.py", line 458, in execute
    14. output = self.handle(*args, **options)
    15. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\base.py", line 106, in wrapper
    16. res = handle_func(*args, **kwargs)
    17. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\commands\migrate.py", line 100, in handle
    18. self.check(databases=[database])
    19. File "D:\software\python3\anconda3\Lib\site-packages\django\core\management\base.py", line 485, in check
    20. all_issues = checks.run_checks(
    21. File "D:\software\python3\anconda3\Lib\site-packages\django\core\checks\registry.py", line 88, in run_checks
    22. new_errors = check(app_configs=app_configs, databases=databases)
    23. File "D:\software\python3\anconda3\Lib\site-packages\django\core\checks\model_checks.py", line 36, in check_all_models
    24. errors.extend(model.check(**kwargs))
    25. File "D:\software\python3\anconda3\Lib\site-packages\django\db\models\base.py", line 1558, in check
    26. *cls._check_indexes(databases),
    27. File "D:\software\python3\anconda3\Lib\site-packages\django\db\models\base.py", line 2002, in _check_indexes
    28. connection.features.supports_expression_indexes
    29. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\functional.py", line 57, in __get__
    30. res = instance.__dict__[self.name] = self.func(instance)
    31. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\mysql\features.py", line 317, in supports_expression_indexes
    32. not self.connection.mysql_is_mariadb
    33. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\functional.py", line 57, in __get__
    34. res = instance.__dict__[self.name] = self.func(instance)
    35. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\mysql\base.py", line 439, in mysql_is_mariadb
    36. return "mariadb" in self.mysql_server_info.lower()
    37. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\functional.py", line 57, in __get__
    38. res = instance.__dict__[self.name] = self.func(instance)
    39. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\mysql\base.py", line 425, in mysql_server_info
    40. return self.mysql_server_data["version"]
    41. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\functional.py", line 57, in __get__
    42. res = instance.__dict__[self.name] = self.func(instance)
    43. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\mysql\base.py", line 399, in mysql_server_data
    44. with self.temporary_connection() as cursor:
    45. File "D:\software\python3\python310\lib\contextlib.py", line 135, in __enter__
    46. return next(self.gen)
    47. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 705, in temporary_connection
    48. with self.cursor() as cursor:
    49. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
    50. return func(*args, **kwargs)
    51. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 330, in cursor
    52. return self._cursor()
    53. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 306, in _cursor
    54. self.ensure_connection()
    55. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
    56. return func(*args, **kwargs)
    57. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 289, in ensure_connection
    58. self.connect()
    59. File "D:\software\python3\anconda3\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
    60. return func(*args, **kwargs)
    61. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 272, in connect
    62. self.init_connection_state()
    63. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\mysql\base.py", line 257, in init_connection_state
    64. super().init_connection_state()
    65. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 239, in init_connection_state
    66. self.check_database_version_supported()
    67. File "D:\software\python3\anconda3\Lib\site-packages\django\db\backends\base\base.py", line 214, in check_database_version_supported
    68. raise NotSupportedError(
    69. django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.36).
    70. E:\data\python\djaongo_prj\guest>

     

    django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.36).

    django.db.utils.NotSupportedError: MySQL 8 or later is required (found 5.7.2)简单快速的解决办法_疯狂的小强呀的博客-CSDN博客

    这个问题是说我们的Django框架版本比较新,已经不支持MySQL老版本5.7.2了,MySQL8或者更新的版本才是我们需要的或者说匹配的。

    解决方案

    从问题出发的解决方案有两个,①卸载老版本的MySQL,安装项目支持的新版本 ②降低Django框架的版本

    pip uninstall django 

    pip install django==2.1.13 

     要重启pycharm

    Error: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试。

    Django-解决报错Error: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试。_Python454的博客-CSDN博客 

     E:\data\python\djaongo_prj\guest>netstat -aon|findstr "8000"
      TCP    0.0.0.0:8000           0.0.0.0:0              LISTENING       14756
      UDP    0.0.0.0:8000           *:*

    PID =14756

    任务管理器 详细信息

     

     

    1. D:\software\python3\python310\python.exe E:/data/python/djaongo_prj/guest/manage.py runserver 127.0.0.1:8001
    2. D:\software\python3\anconda3\Lib\site-packages\numpy\__init__.py:138: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
    3. from . import _distributor_init
    4. D:\software\python3\anconda3\Lib\site-packages\numpy\__init__.py:138: UserWarning: mkl-service package failed to import, therefore Intel(R) MKL initialization ensuring its correct out-of-the box operation under condition when Gnu OpenMP had already been loaded by Python process is not assured. Please install mkl-service package, see http://github.com/IntelPython/mkl-service
    5. from . import _distributor_init
    6. Performing system checks...
    7. System check identified no issues (0 silenced).
    8. You have 16 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions, sign.
    9. Run 'python manage.py migrate' to apply them.
    10. October 02, 2023 - 21:57:38
    11. Django version 2.1.13, using settings 'guest.settings'
    12. Starting development server at http://127.0.0.1:8001/
    13. Quit the server with CTRL-BREAK.

     设置  runserver 127.0.0.1:8001

     启动成功

     删除 数据库中 sign_event  表

    python  manage.py migrate

    1. File "D:\software\python3\anconda3\Lib\site-packages\pymysql\protocol.py", line 221, in raise_for_error
    2. err.raise_mysql_exception(self._data)
    3. File "D:\software\python3\anconda3\Lib\site-packages\pymysql\err.py", line 143, in raise_mysql_exception
    4. raise errorclass(errno, errval)
    5. django.db.utils.OperationalError: (1050, "Table 'sign_event' already exists")
    6. E:\data\python\djaongo_prj\guest>python manage.py migrate
    7. Operations to perform:
    8. Apply all migrations: admin, auth, contenttypes, sessions, sign
    9. Running migrations:
    10. Applying sign.0001_initial... OK
    11. E:\data\python\djaongo_prj\guest>

    重新生成后台管理admin

     python manage.py createsuperuser

    1. E:\data\python\djaongo_prj\guest>python manage.py createsuperuser
    2. Username (leave blank to use 'administrator'): admin
    3. Email address: 11111@qq.com
    4. Password:
    5. Password (again):
    6. Superuser created successfully.

     http://127.0.0.1:8001/admin/

  • 相关阅读:
    AutoCAD Electrical 2022—源箭头和目标箭头
    外呼系统线路不稳定,经常封号怎么办?
    FreeRTOS内存管理分析
    复制活动工作表和计数未保存工作簿进行
    Maya 2024 for Mac(3D建模软件)
    Zebec 生态 AMA 回顾:Nautilus 以及 $ZBC 的未来
    VSCode使用简介
    Tmux 使用教程
    笔记:Python 字典和集合(练习题)
    使用viewerJs替换fastadmin中表格图片预览功能,实现鼠标缩放旋转等功能
  • 原文地址:https://blog.csdn.net/oDianZi1234567/article/details/133471571