Django模型的使用

系统Ubuntu20.04
1.安装Mysql
2.用pip3安装mysqlclient,这个连接Python和Mysql的工具
3.更改配置文件 setting.py其中 DATABASES文件如下。

...
 76 DATABASES = {
 77     'default': {
 78         'ENGINE': 'django.db.backends.mysql',
 79         'NAME': 'sqltest',
 80         'USER': 'root',
 81         'PASSWORD': '',
 82         'HOST': 'localhost',
 83         'PROT': '3306',
 84     }
 85 }

指明了我们要构造一个连接,连接python与root身份登陆的Mysql服务下sqltest数据库。因为没有密码,所以密码是空。

4.手动新建数据库,不然会报错。

mysql ->create database sqltest;

注意名称一致,并且使用分号。

5.使用下列命令,正式创建连接

# python manage.py migrate

即使没有任何模型,也会生成一些系统自带的表,检查如下:


mysql> use sqltest;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_sqltest          |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
+----------------------------+
10 rows in set (0.00 sec)

6.在应用中modles文件创造模型,并且提交这写改变,生成对应的sql语句执行,并且会给你留下调用接口。
6.1创造模型,如下
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)

6.2激活模型。
6.2.1将模型注册到应用
/sqltest/settings.py

INSTALLED_APPS = [
	#下面第一个是模型,根目录是project目录,注意PollsConfig是驼峰体
    "polls.apps.PollsConfig",
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

6.3正式迁移所有polls,注意这时候polls文件已经被包含在project里面了,所以可以别 manage.py发现.

(env) root@Moon:~/workplace/python/virtualenv/env/sqltesttttttt# python3 manage.py makemigrations polls

会有如下输出:

Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Question
    - Create model Choice

6.3.1上面的格式是可以转化为正式的mysql语句的,注意0001_initial.py。使用下面语句,将此文件翻译回Mysql语句。

(env) root@Moon:~/workplace/python/virtualenv/env/sqltesttttttt# python manage.py sqlmigrate polls 0001
--
-- Create model Question
--
CREATE TABLE `polls_question` (
	`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, 		 		  	 
	`question_text` varchar(200) NOT NULL,
	 `pub_data` datetime(6) NOT NULL);
--
-- Create model Choice
--
CREATE TABLE `polls_choice` (
	`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, 	
	`choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL, 
	`question_id` bigint NOT NULL);
ALTER TABLE `polls_choice` 
ADD CONSTRAINT`polls_choice_question_id_c5b4b260_fk_polls_question_id`
FOREIGN KEY (`question_id`) 
REFERENCES `polls_question` (`id`);

6.4应用生成的迁移文件,生成表和操作数据库的api。

(env) root@Moon:~/workplace/python/virtualenv/env/sqltesttttttt# python3 manage.py migrate

为了验证我们的想法,查询数据库sqltest,如下:


mysql> use sqltest;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_sqltest          |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| polls_choice               |
| polls_question             |
+----------------------------+
12 rows in set (0.00 sec)

可以看到,上图的最后两行,出现了我们要的表。

7可以看到基本上的想法和Git是相似的,创造缓冲区,用commit一次性写入所有改变,这里用的是migrate,总的来说包括如下步骤:

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

为模型改变生成迁移文件(makemigrations),之后正式应用迁移文件,创造数据库和api。

8.有了表(定义好了字段,但还是没有填充),和api,我们就要用python操纵数据库 了。使用如下命令,进入到含有生成数据库api的python shell。

(env) root@Moon:~/workplace/python/virtualenv/env/sqltesttttttt# python3 manage.py shell

我们利用这个shell填充一些表的record,来说明我们确实可以用python操作数据库了。


>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet []>
>>> from django.utils import timezone
>>> q=Question( question_text='开会时间', pub_data=timezone.now())
>>> q.save()

注意,创建表时候写错成了pub_data,因此沿用了。
注意,要用save()提交,才能正式生效。接下来,我们检查sqltest库里面的polls_question表,看是否增加了记录,如下:

mysql> use sqltest;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables;
+----------------------------+
| Tables_in_sqltest          |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| polls_choice               |
| polls_question             |
+----------------------------+
12 rows in set (0.00 sec)

mysql> select * from polls_question;
+----+---------------+----------------------------+
| id | question_text | pub_data                   |
+----+---------------+----------------------------+
|  1 | 开会时间      | 2024-06-01 16:36:54.949112 |
+----+---------------+----------------------------+
1 row in set (0.00 sec)

可以看到,确实插入进去了。
(这个其实还是挺麻烦的,不知道有没有更好用的工具,非常自然地把python和mysql结合起来)
ref:
https://docs.djangoproject.com/zh-hans/4.2/intro/tutorial02/
不同的将sqlite3换成了mysql。

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值