Django-website Program Case Series -4 ORM Database operations

Source: Internet
Author: User

Creation of database tables:

When using MySQL, note that the settings in setting.py:

DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ', #mysql的引擎
' NAME ': ', #数据库名
' USER ': ', #数据库用户名
' PASSWORD ': ', #数据库密码
' HOST ': ' 127.0.0.1 ', #数据库host
' PORT ': ' 3306 ', #数据库端口
},
}

You also need to add the MySQL driver to the __init__.py under the project folder:

#django默认使用MySQLdb模块连接mysql
#需要主动修改为pymysql
Import Pymysql
Pymysql.install_as_mysqldb ()

models.py # Create a class in this file

From django.db import Models

# The generated table is named Day1_userinfo
Class UserInfo (models. Model): #创建的类必须继承models. Model
# ID column, self-increment, primary key without user creation Django will create for you yourself a
Username = models. Charfield (MAX_LENGTH=32)
Password = models. Charfield (max_length=64)

In the command-screen execution:
Python manage.py makemigrations #生成临时文件在migrations文件夹中
Python manage.py Migrate #在数据库中生成表

Generated a lot of the tables that Django comes with

database table Basic Operations:

def ORM (Request):
#插入数据
#方式1:
Models. UserInfo.objects.create (username= ' root ', password= ' 123 ',)
#方式2
obj = models. UserInfo (username= ' Zhangjian ', password= ' 123 ')
Obj.save ()
#方式3
DiC ={' username ': ' hapi ', ' Password ': ' 1123 '}
Models. UserInfo.objects.create (**dic)
#查询数据
#查询表出来的是一个django表对象是以列表QuerySet对象
<queryset [<userinfo:userinfo object>, <userinfo:userinfo object>, <userinfo:userinfo Object>] >
result = models. UserInfo.objects.all () #查询所有
result = models. UserInfo.objects.filter (username= ' root ', password= ' 123 ') #条件查询
For row in result: #对表进行循环取出值
Print (Row.id, row.username, Row.password)
#删除操作
Models. UserInfo.objects.filter (username= ' root '). Delete () #删除用户名为root的
#更新操作
Models. UserInfo.objects.all (). Update (password=666) #所有用户密码改成666

Return HttpResponse (' ORM ')

page Operation database Additions and deletions change:

URL Routing configuration:
URL (r ' ^index/', Views.index),
URL (r ' ^user_info/', views.user_info),
URL (r ' ^userdetail-(? p<uid>\d+)/', views.userdetail),
URL (r ' ^userdel-(? p<uid>\d+)/', Views.userdel),
URL (r ' ^usered-(? p<uid>\d+)/', views.usered),
Index.html page:
<! DOCTYPE html>

PY Code:

def index (Request):    return render (Request, ' index.html ')

Query user page user_info.html:

<! DOCTYPE html>

    User Details page userdetail.html:

<! DOCTYPE html>

PY Code:

def user_info (Request):    if Request.method = = "GET":        user_list = models. UserInfo.objects.all ()        print (user_list.query) #查看原生的sql语句    elif Request.method = = "POST":        u = Request. Post.get (' user ')        p = Request. Post.get (' pwd ')        models. UserInfo.objects.create (Username=u, password=p)        return redirect ('/user_info/')    return render (Request, ' Userinfo.html ', {"User_list": User_list})
def userdetail (Request, UID):
obj = models. UserInfo.objects.filter (Id=uid). First () #取id =uid users
return render (Request, ' user_detail.html ', {"obj": obj})

Delete User py code:

def userdel (Request, UID):    models. UserInfo.objects.filter (id=uid). Delete ()    return redirect ('/user_info/')

To modify the user py code:

def usered (Request, UID):    if Request.method = = "GET":        obj = models. UserInfo.objects.filter (Id=uid). First ()        return render (Request, ' usered.html ', {"obj": obj})    elif Request.method = = "POST":        u = Request. Post.get ("username")        p = Request. Post.get ("password")        models. UserInfo.objects.filter (id=uid). Update (Username=u, password=p)        return redirect ('/user_info/')




Django-website Program Case Series -4 ORM Database operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.