• Django学习系列14:第一个数据库迁移


    在Django中,ORM的任务是模型化数据库。

    创建数据库其实是由另一个系统负责的叫做迁移。

    迁移的任务是根据你对models.py文件的改动情况,添加或删除表和列。

    可以把迁移想象成数据库使用的版本控制系统,后面会看到,把应用部署到线上服务器审计数据库时,迁移十分有用。

    现在只需要知道如何创建第一个数据库迁移,使用makemigrations命令创建迁移:

    # python manage.py makemigrations
    Migrations for 'lists':
      lists/migrations/0001_initial.py
        - Create model Item
    # ls lists/migrations/
    0001_initial.py  __init__.py  __pycache__

    Python一开始能给.text属性赋值,继承models.Model的类映射到数据库中的一个表,默认情况下,这种类会得到一个自动生成的id属性,作为表的主键,但是其他列都要自行定义。

    # lists/models.py
    
    from django.db import models
    
    # Create your models here.
    from django.db import models
    
    class Item(models.Model):
        text = models.TextField()

    django提供了很多其他字段类型,IntegerField, CharField, DateField等,使用TextField 而不是CharField,是因为CharField需要限制长度,目前,这个字段的长度是随意的。关于字段类型的更多介绍可以阅读djang教程和文档

    添加新字段就要创建新迁移

    运行测试得到另一个数据库错误# python manage.py test lists

    django.db.utils.OperationalError: no such column: lists_item.text

    出现这个错误的原因是在数据库中添加了一个新字段,所以要再创建一个迁移。

    创建迁移试试

    # python manage.py makemigrations
    You are trying to add a non-nullable field 'text' to item without a default; we can't do that (the database needs something to populate existing rows).
    Please select a fix:
     1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
     2) Quit, and let me add a default in models.py
    Select an option: 2

    这个命令不允许添加没有默认值的列,选择第二个选项,然后在models.py中设定一个默认值。

    class Item(models.Model):
        text = models.TextField(default='')

    现在应该可以顺利创建迁移了。

    # python manage.py makemigrations
    Migrations for 'lists':
      lists/migrations/0002_item_text.py
        - Add field text to item

    在models.py中添加了两行新代码,创建了两个数据库迁移,由此得到的结果是,模型对象上的.text属性能被识别为一个特殊属性了,因此属性的值能保存在数据库中,测试也能通过了

    # python manage.py test lists
    Creating test database for alias 'default'...
    System check identified no issues (0 silenced).
    ....
    ----------------------------------------------------------------------
    Ran 4 tests in 0.105s
    
    OK
    Destroying test database for alias 'default'...

    下面提交创建的第一个模型

    $ git status # see tests.py, models.py, and 2 untracked migrations(看见tests.py, models.py以及两个没有跟踪的迁移文件)
    $ git diff # review changes to tests.py and models.py(审查tests.py and models.py)
    $ git add lists
    $ git commit -m "Model for list Items and associated migration——列表项和相关迁移的模型 "
  • 相关阅读:
    总结在Visual Studio Code创建Node.js+Express+handlebars项目
    【转】nodeJs学习之项目结构
    jquery新版本旧版本之间的坑
    bootstrap使用中遇到的坑
    dataTables基础函数变量
    tabales1.10版参数详解
    【转】自定义(滑动条)input[type="range"]样式
    dataTables工作总结
    转载---SpringBoot+Maven多模块项目(创建、依赖、打包可执行jar包部署测试)完整流程
    MVC模式下的跨域问题
  • 原文地址:https://www.cnblogs.com/ranxf/p/11690305.html
Copyright © 2020-2023  润新知