103-模型和数据库

上一个示例里,我们只是简单的让网页显示我们输入的内容,某种意义上说,它们还不算是数据,因为在代码的世界里,数据都是结构化。

在django中,用模型来设置数据,然后用数据库来存储数据。

1、在test_app的models.py中设置模型。

from django.db import models


# Create your models here.
# 这个模型定义我在cnblogs里新建博文的标题,下含2个属性:文字内容,添加时间
# models是一个包,里面包括很多类,CnbTitle类继承于Model类,两个属性text和date分别是CharField类和DateTimeField类的对象
class CnbTitle(models.Model):
    text = models.CharField(max_length=128)
    date_add = models.DateTimeField(auto_now_add=True)
    
    # 如果要在某个地方区别地显示这个类的对象,使用如下方式
    # 这里表示用类的text属性来指代某个具体的对象
    def __str__(self):
        return self.text

2、激活这个模型。

要激活这个模型很简单,在早先提到的setting中,加入这个模型所在的app即可。

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 添加我们自己添加的app
    'test_app',
]

3、将它们添加到数据库。

市面上有很多数据库,但是在尚未完全了解django之前,可以暂时不必考虑其他数据库,直接使用django内置的sqlite3即可,在setting里有这样一段定义:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

 django使用两条命令来操作数据库,基本上在90%的情况下,这两条命令足够了。

lzhshn@lzhshn-Ryzen:~/PycharmProjects/FreeNote$ python3 manage.py makemigrations
Migrations for 'test_app':
  test_app/migrations/0001_initial.py
    - Create model CnbTitle
lzhshn@lzhshn-Ryzen:~/PycharmProjects/FreeNote$ python3 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, test_app
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 sessions.0001_initial... OK
  Applying test_app.0001_initial... OK
lzhshn@lzhshn-Ryzen:~/PycharmProjects/FreeNote$

可见,python3 manage.py makemigrations会告诉数据库需要给哪些app准备表格,如果不指定,django将会给setting下所有注册的app进行此操作。如果app很多,这个工作可能耗时笔记多,因此也可以指定只给某个app进行准备,将app的名称跟在makemigrations(空格)后即可;

python3 manage.py migrate则是执行真正的操作,可见它的操作对象不仅有我们创建的app:teat_app,还包括了admin,auth等等。

猜你喜欢

转载自www.cnblogs.com/lzhshn/p/11368498.html