django orm 数据库操作

 python manage.py makemigrations

 python manage.py migrate

手动控制台:进入

PS D:\py\devops1> python manage.py shell

导入表

>>> from myapp2.models import User

增   插入记录

>>> User.objects.create(user="zilong",name="子龙",sex="男",age="27",label="网瘾少年")
mysql> show tables;
+----------------------------+
| Tables_in_sunck            |
+----------------------------+
| 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             |
| myapp2_user                |
+----------------------------+
11 rows in set (0.01 sec)

mysql> desc myapp2_user;
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| id    | int          | NO   | PRI | NULL    | auto_increment |
| user  | varchar(30)  | NO   |     | NULL    |                |
| name  | varchar(30)  | NO   |     | NULL    |                |
| sex   | varchar(10)  | NO   |     | NULL    |                |
| age   | int          | NO   |     | NULL    |                |
| label | varchar(100) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

mysql> select * from myapp2_user;
+----+--------+--------+-----+-----+--------------+
| id | user   | name   | sex | age | label        |
+----+--------+--------+-----+-----+--------------+
|  1 | zilong | 子龙   | 男  |  27 | 网瘾少年     |
+----+--------+--------+-----+-----+--------------+
1 row in set (0.00 sec)

插入成功

代码方式:第一导入models   

django orm 数据库操作

 django orm 数据库操作

 查,改,删

# 查看用户
def user_list(request):
    user_list = User.objects.all()
    for user in user_list:
        print(user.name)
        print(user.sex)
    #修改
    obj = User.objects.filter(username="xiangzilong").update(password=123,interest=1)
    #删除
    obj = User.objects.filter(id=1).delete()
    return render(request,"user.html",{"user_list":user_list})

上一篇:python学习笔记(10)Django学习login案例


下一篇:【转】搭建自己的邮件服务器