美文网首页
Django笔记9:数据模型

Django笔记9:数据模型

作者: _百草_ | 来源:发表于2021-08-14 15:54 被阅读0次

Migrations 数据迁移
模型字段参考

1. python manage.py makemigrations创建数据库表

作用:Creates new migration(s) for apps.
注:执行后,需要更新
执行后,按照创建的数据模型(models.py),自动生成app/migrations/0001_initial.py文件

app_label/migrations/0001_initial.py
1.1 models.py 创建数据模型
# -*- coding:utf-8 -*-
from django.db import models
from django.contrib.auth.models import User  # 使用Django的用户管理
from django.utils import timezone

# Create your models here.


class BlogArticles(models.Model):  # 数据表名:app名(小写)+下划线+类名(小写)
    # 博客类,类的一个实例,对应数据库中一条记录
    title = models.CharField(max_length=300)  # 标题,CharField()类型
    # 博客与用户的关系,一个作者多篇文章;将用户表和博客表建立联系
    # on_delete=models.CASCADE,级联删除;即用户删除,用户对应的博客也会被删除
    # related_name="blog_posts",允许类User的实例,以blog_posts属性,反省查询到类BlogArticles的实例
    author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="blog_posts")
    text = models.TextField()  # 博客详情
    publish = models.DateTimeField(default=timezone.now)  # 发布时间

    class Meta:
        ordering = ("-publish",)  # 排序,实例按照publish倒序

    def __str__(self):
        return self.title

1.2 python manage.py makemigrations
C:\testing\py\PycharmProjects\pro_0814>python manage.py makemigrations
Migrations for 'app_0814':
  app_0814\migrations\0001_initial.py  # 自动生成文件
    - Create model BlogArticles  # 创建model

C:\testing\py\PycharmProjects\pro_0814>
1.3 sqlite3 db.sqlite3 查看sqlite3文件
C:\Users\百草\PycharmProjects>sqlite3 pro_0814/db.sqlite3
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> .tables  # sqlite命令,查看当前数据库中所有的数据库表名
app_0814_articles           auth_user_user_permissions
auth_group                  django_admin_log
auth_group_permissions      django_content_type
auth_permission             django_migrations
auth_user                   django_session
auth_user_groups
sqlite>
sqlite> pragma table_info(app_0814_articles);  # sqlite命令:显示数据库表的基本结构
0|id|integer|1||1
1|title|varchar(300)|1||0
2|body|text|1||0
3|publish|datetime|1||0
4|author_id|integer|1||0
sqlite>
上述依次是:cid ,字段名,数据类型,是否为空not null ,dflt_value(不知道是什么), pk外键
1.4 python manage.py sqlmigrate app_label migration_name查看sql语句

作用:Prints the SQL statements for the named migration.
参数说明:
app_label : App label of the application containing the migration.
migration_name : Migration name to print the SQL for.

C:\testing\py\PycharmProjects\pro_0814>python manage.py sqlmigrate app_0814 0001
BEGIN;
--
-- Create model BlogArticles
--
CREATE TABLE "app_0814_blogarticles" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(300) NOT NULL, "text" text NOT NULL, "publish" datetime NOT NULL, "author_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED);
CREATE INDEX "app_0814_blogarticles_author_id_12136d68" ON "app_0814_blogarticles" ("author_id");
COMMIT;

C:\testing\py\PycharmProjects\pro_0814>
1.5 报错信息
  • 错误1:SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xd0
C:\testing\py\PycharmProjects\pro_0814>python manage.py makemigrations
# 报错信息

  File "C:\Users\百草\PycharmProjects\pro_0811\app_0811\models.py", line 25
       ^
SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xd0 in position 3: invalid continuation byte
问题原因1:当前文件有中文,但是没有添加utf-8的注释
  • 警告2:(urls.W005) URL namespace 'admin' isn't unique.
C:\testing\py\PycharmProjects\pro_0811>python manage.py makemigrations
System check identified some issues:

WARNINGS:
?: (urls.W005) URL namespace 'admin' isn't unique. You may not be able to reverse all URLs in this namespace app_0811.Articles.publish: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Migrations for 'app_0811':
  app_0811\migrations\0001_initial.py   # 新增
    - Create model Articles

C:\testing\py\PycharmProjects\pro_0811>
问题原因2:pro_name/urls.py中的urlpatterns中重复定义了admin
解决方法:将重复定义的url注释掉即可
  • 警告3:It seems you set a fixed date / time / datetime value as default for this field.
警告:
HINT: It seems you set a fixed date / time / datetime value as default for this field. 
This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
解决方法:
models.py中default=timezone.now() 修改为 default=timezone.now
  • 警告4:You have 1 unapplied migration(s).
You have 1 unapplied migration(s).Your project may not work properly until you apply the migrations for app(s): app_0814.
Run 'python manage.py migrate' to apply them.

原因:先执行的python manage.py migrate,后创建的python manage.py makemigrations ;所以需要再次执行,否则创建的数据库表并未真正的存放在db.sqlite3

C:\testing\py\PycharmProjects\pro_0814>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, app_0814, auth, contenttypes, sessions
Running migrations:
  Applying app_0814.0001_initial... OK

C:\testing\py\PycharmProjects\pro_0814>

2. python manage.py migrate

pro_name/settingDATABASES 定义了数据库的路径
作用:Updates database schema. Manages both apps with migrations and those without.

C:\testing\py\PycharmProjects\pro_0814>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

C:\testing\py\PycharmProjects\pro_0814>

3. python manage.py createsuperuser 创建超级管理员

C:\testing\py\PycharmProjects\pro_0814>python manage.py createsuperuser
Username: wlh
Email address:
Password:
Password (again):
This password is too short. It must contain at least 8 characters.
This password is too common.
This password is entirely numeric.
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

C:\testing\py\PycharmProjects\pro_0814>

使用创建的超管登录url=127.0.0.1:8000/admin

超管登录
Groups 和Users是应用管理中默认的用户
单击Users可以查看刚刚创建的用户
Users页面

4. 注册到admin

app_label/admin.py 中添加admin.site.register(model.py中创建的类)以注册到admin

# -*- coding:utf-8 -*-
from django.contrib import admin
from app_0814.models import BlogArticles   # 导入类

# Register your models here.
admin.site.register(BlogArticles)  # 注册到admin
注册后展示效果
点击add,进入新增;字段信息同model.py中定义的类属性
已新增的编辑界面

相关文章

网友评论

      本文标题:Django笔记9:数据模型

      本文链接:https://www.haomeiwen.com/subject/ksolbltx.html