- 在浏览器中输入 ip:port/path1/path2/ 程序解析过程
首先根据 urlrs.py解析具体的路径,然后对应的.py文件
比如输入 localhost:8000/test
urls.py
from app01 import views
url(r'^test/', views.yimi)
然后调用app01应用中的views.yimi的函数
- 创建MySQL表
models.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class UserInfo(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=20, null=False)
执行
python manage.py makemigrations
python manage.py migrate
在MySQL中查看数据库
- views.py中调用ORM
views.py
def yimi(request):
ret = models.UserInfo.objects.all() # [UserInfor Object, userInfor Object]
print ret[0].id, ret[0].name
# return HttpResponse("hello")
return render(request, "show_user.html", {"user":ret})
templates/show_user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户</title>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>name</th>
</tr>
{% for i in user %}
<tr>
<th>{{ i.id }}</th>
<th>{{ i.name }}</th>
</tr>
{% endfor %}
</table>
</body>
</html>
- views.py
基本必备三件套
from django.shortcuts import HttpResponse, render, redirect
1. HttpResponse("要返回的内容") => 通常用于直接返回数据
2. render(request, "html文件", {"k1": v1}) => 返回一个HTML文件或者打开文件进行字符串替换
3. redirect("URL") => 告诉用户的浏览器去访问其他的URL
request相关
1. request.method --> 查看请求的方法
2. request.POST --> 获取POST请求的数据
- models.py
查\增\删\改操作
1. 查
book_list = models.Book.objects.all() --> 书对象的列表
2. 增
new_book_obj = models.Book.objects.create(
title="新书的名字",
# publisher=publusher_obj,
publisher_id=7
)
3. 删除
models.Book.objects.get(id=10).delete()
4. 修改
book_obj = models.Book.objects.get(id=9)
book_obj.title=request.POST.get("book_title")
book_obj.publisher_id=9
book_obj.save()
多对一的外键
class Book(models.Model):
id = models.AutoField(primary_key=True) # 自增的ID主键
# 创建一个varchar(64)的唯一的不为空的字段
title = models.CharField(max_length=64, null=False, unique=True)
# 和出版社关联的外键字段
publisher = models.ForeignKey(to="Publisher")