• Django(2)连接MySQL


    修改配置

    打开 dj_web/settings.py

    添加polls配置

    配置中找到 TIME_ZONE = 'UTC' 修改为 TIME_ZONE = 'CN'

    我们需要在以下配置中添加一项

    INSTALLED_APPS = [
        'polls.apps.PollsConfig',       # 我们自己添加的
        'django.contrib.admin',         # 管理员站点
        'django.contrib.auth',          # 认证授权系统
        'django.contrib.contenttypes',  # 内容类型框架
        'django.contrib.sessions',      # 会话框架
        'django.contrib.messages',      # 消息框架
        'django.contrib.staticfiles',   # 管理静态文件的框架
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    MySQL配置

    修改配MySQL置之前我们需要创建一下我们的数据库,我这里的数据库名叫 poll

    我们寻找这个代码块

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': BASE_DIR / 'db.sqlite3',
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    我们并不会使用它,注释掉,在它下方我们添加新的DATABASE配置代码

    DATABASES = {
        'default': {
            # 连接本地mysql数据库
            'ENGINE': 'django.db.backends.mysql',
            'NAME': 'poll',  # 你的数据库名
            'USER': 'root',  # 你的用户名
            'PASSWORD': 'root',  # 你的密码
            'HOST': 'localhost',  # 本地连接
            'PORT': '3306',  # 本地端口号
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    编写 models

    打开 polls/models.py 写入以下代码

    from django.db import models
    
    
    class Question(models.Model):
        question_text = models.CharField(max_length=200)
        pub_date = models.DateTimeField('date published')
    
    
    class Choice(models.Model):
        question = models.ForeignKey(Question, on_delete=models.CASCADE)
        choice_text = models.CharField(max_length=200)
        votes = models.IntegerField(default=0)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    每个模型被表示为 django.db.models.Model 类的子类。每个模型有许多类变量,它们都表示模型里的一个数据库字段。

    每个字段都是 Field 类的实例 - 比如,字符字段被表示为 CharField ,日期时间字段被表示为 DateTimeField 。这将告诉 Django 每个字段要处理的数据类型。

    每个 Field 类实例变量的名字(例如 question_text 或 pub_date )也是字段名,所以最好使用对机器友好的格式。你将会在 Python 代码里使用它们,而数据库会将它们作为列名。

    你可以使用可选的选项来为 Field 定义一个人类可读的名字。这个功能在很多 Django 内部组成部分中都被使用了,而且作为文档的一部分。如果某个字段没有提供此名称,Django
    将会使用对机器友好的名称,也就是变量名。在上面的例子中,我们只为 Question.pub_date 定义了对人类友好的名字。对于模型内的其它字段,它们的机器友好名也会被作为人类友好名使用。

    定义某些 Field 类实例需要参数。例如 CharField 需要一个 max_length 参数。这个参数的用处不止于用来定义数据库结构,也用于验证数据,我们稍后将会看到这方面的内容。

    Field 也能够接收多个可选参数;在上面的例子中:我们将 votes 的 default 也就是默认值,设为0。

    注意在最后,我们使用 ForeignKey 定义了一个关系。这将告诉 Django,每个 Choice 对象都关联到一个 Question 对象。Django 支持所有常用的数据库关系:多对一、多对多和一对一

    激活模型

    这行命令会将 polls/models.py 中的类创建成我们mysql中的表

    py manage.py makemigrations polls
    
    • 1

    出现以下提示为成功

    Migrations for 'polls':
      polls\migrations\0001_initial.py
        - Create model Question
        - Create model Choice
    
    • 1
    • 2
    • 3
    • 4

    通过运行 makemigrations 命令,Django 会检测你对模型文件的修改(在这种情况下,你已经取得了新的),并且把修改的部分储存为一次 迁移。

    迁移是 Django 对于模型定义(也就是你的数据库结构)的变化的储存形式 - 它们其实也只是一些你磁盘上的文件。如果你想的话,你可以阅读一下你模型的迁移数据,它被储存在 polls/migrations/0001_initial.py
    里。别担心,你不需要每次都阅读迁移文件,但是它们被设计成人类可读的形式,这是为了便于你手动调整 Django 的修改方式。

    Django 有一个自动执行数据库迁移并同步管理你的数据库结构的命令 - 这个命令是 migrate,我们马上就会接触它 - 但是首先,让我们看看迁移命令会执行哪些 SQL 语句。sqlmigrate 命令接收一个迁移的名称,然后返回对应的
    SQL:

    sqlmigrate 查看本次迁移会执行的语句

    python manage.py sqlmigrate polls 0001
    
    • 1

    执行迁移

    python manage.py migrate
    
    • 1

    这个 migrate 命令选中所有还没有执行过的迁移(Django 通过在数据库中创建一个特殊的表 django_migrations 来跟踪执行过哪些迁移)并应用在数据库上 - 也就是将你对模型的更改同步到数据库结构上。

    迁移是非常强大的功能,它能让你在开发过程中持续的改变数据库结构而不需要重新删除和创建表 - 它专注于使数据库平滑升级而不会丢失数据。我们会在后面的教程中更加深入的学习这部分内容,现在,你只需要记住,改变模型需要这三步:

    • 编辑 models.py 文件,改变模型。
    • 运行 python manage.py makemigrations 为模型的改变生成迁移文件。
    • 运行 python manage.py migrate 来应用数据库迁移。

    数据库迁移被分解成生成和应用两个命令是为了让你能够在代码控制系统上提交迁移数据并使其能在多个应用里使用;这不仅仅会让开发更加简单,也给别的开发者和生产环境中的使用带来方便。

    可能出现的问题

    Did you install mysqlclient?
    
    • 1

    没有安装 mysqlclient

    pip install mysqlclient
    
    • 1

    数据库API

    进入shell环境

    python manage.py shell
    
    • 1

    测试一下API

    >>> from polls.models import Choice,Question  # 导入我们的两个模型,
    >>> Question.objects.all()  # 查询 question表中所有数据
    <QuerySet []>
    >>> from django.utils import timezone   # 导入时间工具
    >>> q = Question(question_text="what's new?",pub_date=timezone.now()) # 插入一条数据
    >>> q.save()  # 保存
    >>> q.id  # 输出id
    1
    >>> q.question_text # 输出 问题文本
    "what's new?"
    >>> q.pub_date  # 输出 发布时间
    datetime.datetime(2022, 12, 3, 11, 19, 11, 226006, tzinfo=datetime.timezone.utc)
    >>> q.question_text = "what's up" # 修改问题文本
    >>> q.save()  # 保存
    >>> q.question_text # 展示
    "what's up"
    >>> Question.objects.all()  # 展示question表所有数据
    <QuerySet [<Question: Question object (1)>]>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    对于我们了解这个对象的细节没什么帮助。让我们通过编辑 Question 模型的代码(位于 polls/models.py 中)来修复这个问题。给 Question 和 Choice 增加 str() 方法。

    from django.db import models
    
    
    class Question(models.Model):
        ...
        def __str__(self):
            return self.question_text
    
    
    class Choice(models.Model):
        ...
        def __str__(self):
            return self.choice_text
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    给模型增加 str() 方法是很重要的,这不仅仅能给你在命令行里使用带来方便,Django 自动生成的 admin 里也使用这个方法来表示对象。

    让我们再为此模型添加一个自定义方法:

    import datetime
    
    from django.db import models
    from django.utils import timezone
    
    
    class Question(models.Model):
        ...
        def was_published_recently(self):
            return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    新加入的 import datetime 和 from django.utils import timezone 分别导入了 Python 的标准 datetime 模块和 Django 中和时区相关的 django.utils.timezone 工具模块。

    保存文件然后通过 python manage.py shell 命令再次打开 Python 交互式命令行:

    >>> from polls.models import Choice, Question
    
    # Make sure our __str__() addition worked.
    >>> Question.objects.all()
    <QuerySet [<Question: What's up?>]>
    
    # Django provides a rich database lookup API that's entirely driven by
    # keyword arguments.
    >>> Question.objects.filter(id=1)
    <QuerySet [<Question: What's up?>]>
    >>> Question.objects.filter(question_text__startswith='What')
    s up?>]>
    
    # Get the question that was published this year.
    >>> from django.utils import timezone
    >>> current_year = timezone.now().year
    >>> Question.objects.get(pub_date__year=current_year)
    <Question: What's up?>
    
    # Request an ID that doesn't exist, this will raise an exception.
    >>> Question.objects.get(id=2)
    Traceback (most recent call last):
        ...
    DoesNotExist: Question matching query does not exist.
    
    # Lookup by a primary key is the most common case, so Django provides a
    # shortcut for primary-key exact lookups.
    # The following is identical to Question.objects.get(id=1).
    >>> Question.objects.get(pk=1)
    <Question: What's up?>
    
    # Make sure our custom method worked.
    >>> q = Question.objects.get(pk=1)
    >>> q.was_published_recently()
    True
    
    # Give the Question a couple of Choices. The create call constructs a new
    # Choice object, does the INSERT statement, adds the choice to the set
    # of available choices and returns the new Choice object. Django creates
    # a set to hold the "other side" of a ForeignKey relation
    # (e.g. a question's choice) which can be accessed via the API.
    >>> q = Question.objects.get(pk=1)
    
    # Display any choices from the related object set -- none so far.
    >>> q.choice_set.all()
    <QuerySet []>
    
    # Create three choices.
    >>> q.choice_set.create(choice_text='Not much', votes=0)
    <Choice: Not much>
    >>> q.choice_set.create(choice_text='The sky', votes=0)
    <Choice: The sky>
    >>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)
    
    # Choice objects have API access to their related Question objects.
    >>> c.question
    <Question: What's up?>
    
    # And vice versa: Question objects get access to Choice objects.
    >>> q.choice_set.all()
    , , ]>
    >>> q.choice_set.count()
    3
    
    # The API automatically follows relationships as far as you need.
    # Use double underscores to separate relationships.
    # This works as many levels deep as you want; there's no limit.
    # Find all Choices for any question whose pub_date is in this year
    # (reusing the 'current_year' variable we created above).
    >>> Choice.objects.filter(question__pub_date__year=current_year)
    <QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
    
    # Let's delete one of the choices. Use delete() for that.
    >>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
    >>> c.delete()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
  • 相关阅读:
    项目管理-2023西电网课课后习题答案-第五章
    UVA-122 树的层次遍历 题解答案代码 算法竞赛入门经典第二版
    网络安全中的POC、EXP、Payload、ShellCode
    Python分布式动态页面爬虫研究
    SVG图形
    Docker从入门到进阶之基础操作(3)—— 仓库(Repository)
    Win11的两个实用技巧系列之电脑死机解决办法
    践行“双碳” 迈动互联节能数据产品上线
    mybatis 调用修改SQL时 出现了一个问题 没有修改成功也没有报错
    基于数据驱动的变电站巡检机器人自抗扰控制
  • 原文地址:https://blog.csdn.net/gtd54789/article/details/128167673