【Django学习笔记】3:在业务逻辑中使用内置的SQLite数据库

注册自定的app

在同名子目录下的settings.py中注册这个自定的app:

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # 在这里注册了自定的app
    'lzhapp',
]

配置要使用的数据库

在同名子目录下的settings.py中配置要使用的数据库相关信息:

# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases

DATABASES = {
    # 默认使用的数据库
    'default': {
        # sqlite3的数据库驱动
        'ENGINE': 'django.db.backends.sqlite3',
        # 使用sqlite3数据库
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

编写模型层

Django虽然是MTV框架,但其中的M和V与MVC框架基本是一致的,所以也需要模型层。模型层在同名子目录下的models.py中配置:

from django.db import models


# Create your models here.

# 模型层,用户信息类,继承Model类
class UserInfo(models.Model):
    # 用户名字段,类型是长度为32的char字符串
    usr = models.CharField(max_length=32)
    # 密码字段,类型是长度为32的char字符串
    pwd = models.CharField(max_length=32)

makemigrations

在对模型层文件进行配置以后,在PyCharm命令行使用:

python manage.py makemigrations

具体出现:

E:\WorkSpace\PyCharm\lzhDjango>python manage.py makemigrations
Migrations for 'lzhapp':
  lzhapp\migrations\0001_initial.py
    - Create model UserInfo

E:\WorkSpace\PyCharm\lzhDjango>

在同名子目录下的migrations/子目录下,出现了一个文件:
这里写图片描述
这个文件的内容是:

# Generated by Django 2.0.5 on 2018-06-27 07:49

from django.db import migrations, models


class Migration(migrations.Migration):

    initial = True

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='UserInfo',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('usr', models.CharField(max_length=32)),
                ('pwd', models.CharField(max_length=32)),
            ],
        ),
    ]

这条命令即是要生成这个文件,这个文件意在记录对模型层的改动,但这些改动还没有写入数据库。

migrate

继续,在PyCharm命令行使用:

python manage.py migrate

具体出现:

E:\WorkSpace\PyCharm\lzhDjango>python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, lzhapp, 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 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 lzhapp.0001_initial... OK
  Applying sessions.0001_initial... OK

E:\WorkSpace\PyCharm\lzhDjango>

此时,对模型层的改动已经依据上一步所生成的文件全部提交到数据库中。

与数据库交互的业务逻辑

Django自带一个ORM框架,可以像Hibernate那样操作数据库。修改app目录下的views.py文件,在其中操作数据库:

from django.shortcuts import render
# 导入要使用的模型层文件
from lzhapp import models


# 路由中指定要调用的函数,传入一个用户请求参数
def index(request):
    # 从数据库中读取所有数据
    inptDicLst = models.UserInfo.objects.all()
    # 返回一个页面,如返回自己这个页面本身,第三个参数以字典方式提供数据对象
    return render(request, 'index.html', {'lst': inptDicLst})


# 表单提交调用的函数
def gosub(request):
    # 相当于Java的Servlet中的doPost情况
    if request.method == 'POST':
        # 获取表单提交来的数据
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        # 在控制台输出表单的提交看一下
        print(username, password)
        # 将数据添加到数据库,而不像之前那样使用全局变量列表
        models.UserInfo.objects.create(usr=username, pwd=password)
    # 从数据库中读取所有数据
    inptDicLst = models.UserInfo.objects.all()
    # 返回一个页面,如返回自己这个页面本身,第三个参数以字典方式提供数据对象
    return render(request, 'index.html', {'lst': inptDicLst})

测试运行

访问http://localhost:8000/index/
这里写图片描述
提交一些数据:
这里写图片描述
关闭程序,再重新打开,然后访问这个网址,仍然能看到刚刚提交的数据,这就是与不使用数据库的区别。

猜你喜欢

转载自blog.csdn.net/shu15121856/article/details/80830511