这片博文来详细说明django模型的使用,涉及到django模型的创建,字段介绍,以及django模型的crud操作,以及一对一等操作。

在使用模型之前,我们首先设置数据库选项,django的默认数据库时sqlite3,这里我们设置数据库引擎为mysql。

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "webinfo",
        'USER': "root",
        "PASSWORD": "123456",
        "PORT": 3306,
        "HOST": "10.0.102.222",
    }
}

#这里的参数也就是连接数据库需要的参数,其中name表示的是连接到数据库的哪个库。需要注意的是除了使用django默认引擎外,其余的引擎都需要在对应的数据库上创建对应的数据库。

#MySQL创建对应的数据库语句如下!
MariaDB [mytest]> create database webinfo character set utf8;
Query OK, 1 row affected (0.01 sec)

django模型中的字段类型

熟悉MySQL数据库的话就会知道字段类型的含义,同样django中也为各种各样的信息设置了字段,选择合适的字段对数据的正确存储至关重要,这里会详细说明django中的字段类型。

首先来看一下官方文档的一个实例:在models.py中,我们写入了如下代码,这个代码创建了一个Person类,定义了两个类属性。

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)

执行如下操作:

E:\pycharm\web\testmodel>python2 manage.py makemigrations
Migrations for 'mysite':
  mysite\migrations\0001_initial.py:
    - Create model Person             #创建了模块Person

E:\pycharm\web\testmodel>python2 manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, mysite, 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 mysite.0001_initial... OK
命令的结果是在数据库中创建了对应的表

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-13
  • 2022-02-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-31
猜你喜欢
  • 2022-12-23
  • 2021-08-02
  • 2021-11-20
  • 2021-11-20
  • 2022-12-23
  • 2021-07-08
  • 2021-08-22
相关资源
相似解决方案