Django(重点)

一、创建数据库

1. 创建和修改数据库表   
在settings中的配置app的名字app02
python manage.py makemigrations
python manage.py migrate
2. 数据库操作 增删改查 """
models操作
from django.db import models

# Create your models here.

# 在数据库创建表,表名userinfo
class UserInfo(models.Model):
    name = models.CharField(max_length=16) # 表中创建一列数据
    age = models.IntegerField()

class Group(models.Model):
    caption = models.CharField(max_length=16)

# userinfo
"""
id            name(字符串类型)     age
1             root                 18
2             eric                 20
"""
views操作
from django.shortcuts import render
from django.shortcuts import HttpResponse

# Create your views here.
from app02 import models
def test(request):
    # 增加
    # name,age表示列名
    # models.UserInfo.objects.create(name='alex',age=18)
    # models.Group.objects.create(caption='组2')

    # 获取
    # user_list = models.UserInfo.objects.all()
    #[{id:1,name:root,age:18},{id:1,name:root,age:18},]

    # 删除
    # models.UserInfo.objects.all().delete()
    # models.UserInfo.objects.all().delete()
    # models.UserInfo.objects.filter(id=1).delete()
    # models.UserInfo.objects.filter(age=18).delete()
    # models.UserInfo.objects.filter(id=2,age=18).delete()
    # models.UserInfo.objects.filter(id=2,age=18,name='root').delete()

    # 更新
    # models.UserInfo.objects.all().update(age=10)
    # models.UserInfo.objects.filter(name='alex').update(age=10)
    # models.UserInfo.objects.filter(id=1).update(age=10)
    # models.UserInfo.objects.filter(id=1).update(age=10, name='tony')

    # for row in user_list:
    #     print(row.id,row.name,row.age)
    # return HttpResponse('ok')
    # 1.找test.html文件,并打开获取其内容
    # 2.将获取到的内容+{'user_list': user_list}参数进行替换
    # 3.将替换后的字符串返回给用户
    return render(request,'test.html',{'uuu': user_list})

def add_test(request):
    n = request.GET.get('name')
    a = request.GET.get('age')
    models.UserInfo.objects.create(name=n,age=a)
    return HttpResponse('创建成功')

def del_text(request):
    nid=request.GET.get('iid')
    models.sutdent.objects.filter(id=nid).delete()
    return HttpResponse('删除成功')

def edit_text(request):
    i=request.GET.get('id')
    n=request.GET.get('name')
    a=request.GET.get('age')
    models.sutdent.objects.filter(id=i).update(name=n,age=a)
    return HttpResponse('更新成功')
url操作:同时返回给用户
 url(r'^test.html$', views.test),
    url(r'^add_test.html$', views.add_test),
    url(r'^del_test.html$', views.del_test),
    url(r'^edit_test.html$', views.edit_test),
html操作:(创建,和删除,更新)
创建
http://127.0.0.1/add_text/?name=nihao&age=17
删除
http://127.0.0.1/del_text/?id=2
更新
http://127.0.0.1:8000/edit_text/?id=3&name=iiei&age=22


 

 

 


 


 


posted @ 2017-03-08 09:21  打不死的--蟑螂  阅读(303)  评论(0编辑  收藏  举报