Go教程

django orm 数据库操作

本文主要是介绍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   

 

 查,改,删

# 查看用户
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})

这篇关于django orm 数据库操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!