首页 > 代码库 > django(四)

django(四)

一、数据调用下拉菜单内容

 

viwes.py

from django.shortcuts import render,HttpResponse,render_to_responsefrom django import formsfrom app01 import modelsclass IndexForm(forms.Form):    # c = [    #     (1,‘CEO‘),    #     (2,‘COO‘)    # ]    c = models.UserType.objects.all().values_list(id,caption)    user_type_id = forms.IntegerField(widget=forms.Select(choices=c))    def __init__(self,*args, **kwargs):                                         #这段目的添加完用户类型,网页立即显示        # 父类构造方法:1、获取所有静态字段   2、fields = []        super(IndexForm, self).__init__(*args, **kwargs)        # print(self.fields[‘user_type_id‘].widget.choices)        self.fields[user_type_id].widget.choices = models.UserType.objects.all().values_list(id,caption)def index(request):    # for i in range(10):                                              #添加表数据    #     models.UserType.objects.create(caption=‘CE‘+str(i))                  # c = models.UserType.objects.all().count()    # print(c)    form = IndexForm()    return render(request, index.html, {form: form})def add_user_type(request):                         #get http://127.0.0.1:8000/add_user_type?q=CVO   方式可以添加用户类型CVO    q = request.GET.get(q, None)    if q:        models.UserType.objects.create(caption=q)    return HttpResponse(q)

 

model.py

from django.db import models# Create your models here.class UserType(models.Model):    caption = models.CharField(max_length=16)

显示效果

 

 

技术分享

 

二、

model操作 F/Q
F:
temp = salary+500
models.UserInfo.objects.filter().update(salary=temp)
update userinfo set salary=salary+500

from django.db.models import F
models.UserInfo.objects.filter().update(salary=F(‘salary‘)+500)

Q:
构造搜索条件
1、传参
models.UserInfo.objects.filter(id=123,name=‘alex‘)

2、传字典
d = {‘id‘: 123, ‘name‘:‘alex‘}
models.UserInfo.objects.filter(**d)

<input name=‘id‘ />
<input name=‘name‘ />
获取用户输入,并构造成字典:
models.UserInfo.objects.filter(**c)
3、传Q对象
models.UserInfo.objects.filter(Q对象)

viwes.py

def index(request):    form = IndexForm()    from django.db.models import Q    """    q1 = Q()    q1.connector = ‘OR‘    q1.children.append((‘id‘, 1))    q1.children.append((‘id‘, 2))    q1.children.append((‘id‘, 3))    # 1 CE0    # 2 CE1    # 3 CE2    obj = models.UserType.objects.filter(q1)    for item in obj:        print(item.id,item.caption)    """    con = Q()    q1 = Q()    q1.connector = OR    q1.children.append((id, 1))    q1.children.append((id, 2))    q1.children.append((id, 3))    q2 = Q()    q2.connector = OR    q2.children.append((caption, CE1))    q2.children.append((caption, CE2))    con.add(q1, AND)    con.add(q2, AND)    obj = models.UserType.objects.filter(con)    for item in obj:        print(item.id,item.caption)    return render(request, index.html, {form: form})
    # 2 CE1    # 3 CE2

 

 

三、中间件

django(四)