django进阶

Posted MKY-技术驿站

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django进阶相关的知识,希望对你有一定的参考价值。

,多对多:
创建多对多:
方式一:自定义关系表

class Host(models.Model):
    nid=models.AutoField(primary_key=True)
    hostname=models.CharField(max_length=32,db_index=True)
    ip=models.GenericIPAddressField(db_index=True)
    port=models.IntegerField()
    b=models.ForeignKey(\'Business\',to_field=\'id\')

#自定义关联
class HostToApp(models.Model):
     hobj=models.ForeignKey(to=\'Host\',to_fields=\'nid\')
     aobj=models.ForeignKey(to=\'Application\',to_fields=\'id\')

对表的操作和foreignkey一样,并且可以直接对这个表进行操作
HostToApp.objects.create(hobj_id=1,aobj_id=2)



方式二:自动创建关系表

 1 class Host(models.Model):
 2     nid=models.AutoField(primary_key=True)
 3     hostname=models.CharField(max_length=32,db_index=True)
 4     ip=models.GenericIPAddressField(db_index=True)
 5     port=models.IntegerField()
 6     b=models.ForeignKey(\'Business\',to_field=\'id\')
 7 
 8 class Application(models.Model):
 9       name=models.CharField(max_length=64)
10       auto=models.ManyToManyField("Host")

缺点就是无法直接对第三张表进行操作,只能间接的方式来操作并且也无法在这个表增加多余字段
#现获取对象
obj = Application.objects.get(id=1)

# 然后间接操作第三张表中的内容

#增加
obj.r.add(1)#Application=1  host=1   obj中已经存在了app id 所以这里的add=1就是host表中的id
obj.r.add(2)#Application=1  host=2
obj.r.add(2,3,4)#Application=1  host=2/3/4  
obj.r.add(*[1,2,3,4])

#移除
obj.r.remove(1)
obj.r.remove(2,4)
obj.r.remove(*[1,2,3])

#清空obj中的app  id =1的所有内容
obj.r.clear()

#更新
obj.r.set([3,5,7])

# 所有相关的主机对象“列表” QuerySet
obj.r.all()

 

增删改查例子  

def app(reques):
    obj=models.Application.objects.all()
    print(obj)
    for i in obj:
        #查询
        print(i.name,i.auto.all())

    #增加app项目并且返回这个obj对象
    #obj=models.Application.objects.create(name=\'oracle\')
    #增加1,3,4host到app
    #obj.auto.add(*[1,4,3])


    #删除
    # obj=models.Application.objects.get(id=1)
    # obj.auto.remove(1)
    # return render(reques,\'app.html\',{\'obj\':obj})
    return HttpResponse("ok")

 

 

获取用户请求头

def test(request):
    #查看源码
    #<class \'django.core.handlers.wsgi.WSGIRequest\'>
    from django.core.handlers.wsgi import WSGIRequest
    print(type(request))
    #查询
    for x,v in request.environ.items():
        print(x,v)
    return HttpResponse("Ok")

结果(用到最多的就是HTTP_USER_AGENT,判断客户端用的什么设备类型):

 1 (\'TMP\', \'C:\\\\Users\\\\ADMIN~1.MEN\\\\AppData\\\\Local\\\\Temp\')
 2 (\'PYTHONIOENCODING\', \'UTF-8\')
 3 (\'COMPUTERNAME\', \'MENKEYI\')
 4 (\'wsgi.multiprocess\', False)
 5 (\'PROCESSOR_LEVEL\', \'6\')
 6 (\'RUN_MAIN\', \'true\')
 7 (\'HTTP_COOKIE\', \'csrftoken=mjMaE6agb2Si4NrdFacQpUIkviQIFv3C; _ga=GA1.1.627222119.1494076915; Hm_lvt_a033dafefef77193d4d80cc7103c9772=1493689044,1494076914,1494228704,1\'494597132\')
 8 (\'USERDOMAIN\', xxxxxxxx\')
 9 (\'GOROOT\', \'C:\\\\Go\\\\app\')
10 (\'SERVER_PROTOCOL\', \'HTTP/1.1\')
11 (\'SERVER_SOFTWARE\', \'WSGIServer/0.1 Python/2.7.9\')
12 (\'PSMODULEPATH\', \'C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\Modules\\\\\')
13 (\'SCRIPT_NAME\', u\'\')
14 (\'COMMONPROGRAMFILES\', \'C:\\\\Program Files\\\\Common Files\')
15 (\'PROCESSOR_IDENTIFIER\', \'Intel64 Family 6 Model 70 Stepping 1, GenuineIntel\')
16 (\'REQUEST_METHOD\', \'GET\')
17 (\'wsgi.version\', (1, 0))
18 (\'PROGRAMFILES\', \'C:\\\\Program Files\')
19 (\'PROCESSOR_REVISION\', \'4601\')
20 (\'SYSTEMROOT\', \'C:\\\\Windows\')
21 (\'QUERY_STRING\', \'\')
22 (\'PATH\', \'C:\\\\ProgramData\\\\Oracle\\\\Java\\\\javapath;C:\\\\Program Files (x86)\\\\Common Files\\\\NetSarang;C:\\\\Program Files (x86)\\\\Intel\\\\iCLS Client\\\\;C:\\\\Program Files\\\\Intel\\\\iCLS Client\\\\;C:\\\\Windows\\\\system32;C:\\\\Windows;C:\\\\Windows\\\\System32\\\\Wbem;C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;C:\\\\Program Files\\\\Intel\\\\Intel(R) Management Engine Components\\\\DAL;C:\\\\Program Files\\\\Intel\\\\Intel(R) Management Engine Components\\\\IPT;C:\\\\Program Files (x86)\\\\Intel\\\\Intel(R) Management Engine Components\\\\DAL;C:\\\\Program Files (x86)\\\\Intel\\\\Intel(R) Management Engine Components\\\\IPT;C:\\\\Program Files\\\\Intel\\\\WiFi\\\\bin\\\\;C:\\\\Program Files\\\\Common Files\\\\Intel\\\\WirelessCommon\\\\;C:\\\\Program Files\\\\Hewlett-Packard\\\\SimplePass\\\\;C:\\\\Program Files\\\\Microsoft SQL Server\\\\110\\\\Tools\\\\Binn\\\\;C:\\\\Python27;C:\\\\Python27\\\\Scripts;C:\\\\Program Files (x86)\\\\mysql\\\\MySQL Server 5.5\\\\bin;C:\\\\Python27\\\\Lib\\\\site-packages\\\\Django-1.7.7-py2.7.egg\\\\django\\\\bin;C:\\\\Program Files (x86)\\\\IDM Computer Solutions\\\\UltraEdit;C:\\\\Program Files\\\\Windows Imaging\\\\;C:\\\\Program Files (x86)\\\\OpenVPN\\\\bin;C:\\\\Program Files\\\\Git\\\\cmd;C:\\\\Go\\\\bin;d:\\\\Program Files (x86)\\\\erl5.10.4\\\\bin;D:\\\\Program Files (x86)\\\\RabbitMQ Server\\\\rabbitmq_server-3.2.4\\\\sbin\')
23 (\'PYTHONUNBUFFERED\', \'1\')
24 (\'PROGRAMFILES(X86)\', \'C:\\\\Program Files (x86)\')
25 (\'#ENVKKPRBC_CMDILNE\', \'\')
26 (\'CONTENT_LENGTH\', \'\')
27 (\'HTTP_UPGRADE_INSECURE_REQUESTS\', \'1\')
28 (\'HTTP_CACHE_CONTROL\', \'max-age=0\')
29 (\'HTTP_CONNECTION\', \'keep-alive\')
30 (\'REMOTE_HOST\', \'\')
31 (\'TEMP\', \'C:\\\\Users\\\\ADMIN~1.MEN\\\\AppData\\\\Local\\\\Temp\')
32 (\'REMOTE_ADDR\', \'127.0.0.1\')
33 (\'COMMONPROGRAMFILES(X86)\', \'C:\\\\Program Files (x86)\\\\Common Files\')
34 (\'#ENVTSLOGRBCSHELLEXT3340\', \'64101024\')
35 (\'PROCESSOR_ARCHITECTURE\', \'AMD64\')
36 (\'wsgi.url_scheme\', \'http\')
37 (\'ALLUSERSPROFILE\', \'C:\\\\ProgramData\')
38 (\'SHELLLAUNCH{A81BA54B-CCFE-4204-8E79-A68C0FDFA5CF}\', \'ShellExt\')
39 (\'LOCALAPPDATA\', \'C:\\\\Users\\\\admin.menkeyi\\\\AppData\\\\Local\')
40 (\'HOMEPATH\', \'\\\\Users\\\\admin.menkeyi\')
41 (\'USERDOMAIN_ROAMINGPROFILE\', \'xxxxxx\')
42 (\'VS120COMNTOOLS\', \'D:\\\\Program Files (x86)\\\\Microsoft Visual Studio 12.0\\\\Common7\\\\Tools\\\\\')
43 (\'ERLANG_HOME\', \'d:\\\\Program Files (x86)\\\\erl5.10.4\')
44 (\'USERNAME\', \'admin\')
45 (\'HTTP_ACCEPT\', \'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\')
46 (\'#ENVTSLOGSSS3340\', \'64102944\')
47 (\'LOGONSERVER\', \'\\\\\\\\MENKEYI\')
48 (\'COMSPEC\', \'C:\\\\Windows\\\\system32\\\\cmd.exe\')
49 (\'PROGRAMDATA\', \'C:\\\\ProgramData\')
50 (\'wsgi.file_wrapper\', <class wsgiref.util.FileWrapper at 0x0000000003A08E88>)
51 (\'PYTHONPATH\', \'E:\\\\mydjango\')
52 (\'RABBITMQ_SERVER\', \'D:\\\\Program Files (x86)\\\\RabbitMQ Server\')
53 (\'wsgi.multithread\', True)
54 (\'wsgi.input\', <socket._fileobject object at 0x0000000003C0AA20>)
55 (\'HTTP_USER_AGENT\', \'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36\')
56 (\'HTTP_HOST\', \'127.0.0.1:8000\')
57 (\'SESSIONNAME\', \'Console\')
58 (\'PATHEXT\', \'.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC\')
59 (\'PATH_INFO\', u\'/app01/test/\')
60 (\'FP_NO_HOST_CHECK\', \'NO\')
61 (\'WINDIR\', \'C:\\\\Windows\')
62 (\'#ENVTSLOGTSLOG3340\', \'64101664\')
63 (\'HTTP_ACCEPT_ENCODING\', \'gzip, deflate, sdch, br\')
64 (\'SERVER_PORT\', \'8000\')
65 (\'MOZ_PLUGIN_PATH\', \'C:\\\\Program Files (x86)\\\\Foxit Software\\\\Foxit Reader\\\\plugins\\\\\')
66 (\'HOMEDRIVE\', \'C:\')
67 (\'SERVER_NAME\', \'axxxxxi\')
68 (\'wsgi.run_once\', False)
69 (\'#ENVTSLOGXMEDIALIBRARY3340\', \'280591264\')
70 (\'SYSTEMDRIVE\', \'C:\')
71 (\'GATEWAY_INTERFACE\', \'CGI/1.1\')
72 (\'HTTP_ACCEPT_LANGUAGE\', \'zh-CN,zh;q=0.8\')
73 (\'PYCHARM_HOSTED\', \'1\')
74 (\'NUMBER_OF_PROCESSORS\', \'8\')
75 (\'APPDATA\', \'C:\\\\Users\\\\admin.menkeyi\\\\AppData\\\\Roaming\')
76 (\'DJANGO_SETTINGS_MODULE\', \'mydjango.settings\')
77 (\'PROGRAMW6432\', \'C:\\\\Program Files\')
78 (\'CONTENT_TYPE\', \'text/plain\')
79 (\'wsgi.errors\', <open file \'<stderr>\', mode \'w\' at 0x00000000020FB150>)
80 (\'COMMONPROGRAMW6432\', \'C:\\\\Program Files\\\\Common Files\')
81 (\'OS\', \'Windows_NT\')
82 (\'PUBLIC\', \'C:\\\\Users\\\\Public\')
83 (\'USERPROFILE\', \'C:\\\\Users\\\\admin\')
View Code

 

 

 

分页(手动写)

view

  1 def user_list(request):
  2     #模拟数据库数据
  3     users=range(200)
  4 
  5     #从前端接受过来的都是字符串,request.GET.get(\'p\',1)如果p为空那么值为1
  6     #获取当前页
  7     curr_pager_num=int(request.GET.get(\'p\',1))
  8 
  9     #每个页面显示几条数据
 10     page_data_num=10
 11 
 12 
 13 
 14     #开始索引
 15     start=(curr_pager_num-1)*page_data_num
 16     #结束索引
 17     end=curr_pager_num*page_data_num
 18     #根据star和end做页面数据切分
 19     data=users[start:end]
 20 
 21     #获取数据总页数
 22     all_count=len(users)
 23 
 24     #计算分页数量
 25     total_count,y=divmod(all_count,page_data_num)
 26     #y>1分页就总数就加1
 27     if y:
 28         total_count += 1
 29 
 30     #存储分页内容列表
 31     page_str_list=[]
 32 
 33     #页面页码尽量是基数不能小于5
 34     pager_num=11
 35 
 36     #总页数小于11
 37     if total_count < pager_num :
 38         start_index=1
 39         end_index=total_count+1
 40 
 41     else:
 42         #当前页小于6
 43         if curr_pager_num  <6:
 44             start_index=1
 45             #end_index=11 + 1
 46             end_index=pager_num + 1
 47         else:
 48             #总页数大于11:start_index= curr_pager_num -5
 49             start_index= curr_pager_num - (pager_num - 1)/2
 50             #end_index=curr_pager_num + 6
 51             end_index=curr_pager_num + (pager_num + 1)/2
 52             #curr_pager_num+ 5)
 53             if (curr_pager_num+ (pager_num - 1)/2) > total_count:
 54                 #start_index=total_count - 11 + 1
 55                 start_index=total_count - pager_num + 1
 56                 end_index=total_count+1
 57 
 58 
 59     if curr_pager_num ==1:
 60         prev=\'<a class="page" href="javascript:void(0)">上一页</a>\'
 61     else:
 62         #上一页
 63         prev=\'<a class="page" href="/user_list/?p=%s">上一页</a>\'%(curr_pager_num - 1)
 64     page_str_list.append(prev)
 65     #循环增加
 66     for i in range(int(start_index),int(end_index)):
 67 
 68         #当前页面class中增加active属性
 69         if i == curr_pager_num:
 70             temp=\'<a class="page active" href="/user_list/?p=%s">%s</a>\'%(i,i)
 71         else:
 72             temp=\'<a class="page" href="/user_list/?p=%s">%s</a>\'%(i,i)
 73 
 74         #追加到列表
 75         page_str_list.append(temp)
 76 
 77 
 78     #当前页等于最大页数就不在加1
 79     if curr_pager_num  == total_count:
 80         next_page=\'<a class="page" href="javascript:void(0)">下一页</a>\'
 81     else:
 82        next_page=\'<a class="page" href="/user_list/?p=%s">下一页</a>\'%(curr_pager_num + 1)
 83     page_str_list.append(next_page)
 84 
 85 
 86     #跳转页
 87     jump="""
 88     <input type=\'text\'/><a onclick=\'jumpTo(this,"/user_list/?p=")\' id=\'jump_id\'>GO</a>
 89     <script>
 90         function jumpTo(ths,base){
 91              var val = ths.previousSibling.value;
 92              location.href = base + val;
 93         }
 94     </script>
 95     """
 96     page_str_list.append(jump)
 97 
 98     #将列表进行字符串拼接返回前端
 99     page_str="".join(page_str_list)
100 
101 
102 
103     #page_str=mark_safe("",join(page_list))前端将信任这代码
104 
105     return render(request,\'user_list.html\',{\'li\':data,\'page_str\':page_str})
View Code

url

url(r\'^user_list/$\', views.user_list),

html,中的incloud 的html和上一个例子中的一样

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <style>
 7             .pagediv .page{
 8                 display: inline-block;
 9                 padding: 5px;
10                 background-color: aqua;
11                 margin: 5px;
12             }
13         .pagediv .page.active{
14             background-color: darkgreen;        }
15     </style>
16 </head>
17 <body>
18 
19 <ul >
20     {% include \'li.html\' %}
21 </ul>
22 <div class="pagediv">
23      {{ page_str|safe }}
24 </div>
25 </body>
26 </html>
html
1 {% for user in li %}
2   <li> {{ user }}</li>
3 {% endfor %}
include li.html

 

 

将上面的代码改造成类方式实现

view

 1 from  utlis import pagination
 2 
 3 def user_list(request):
 4     #模拟数据库数据
 5     users=range(200)
 6 
 7     #获取当前页
 8     current_page = request.GET.get(\'p以上是关于django进阶的主要内容,如果未能解决你的问题,请参考以下文章

Atom编辑器入门到精通 Atom使用进阶

Django进阶

我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段

我的C语言学习进阶之旅解决 Visual Studio 2019 报错:错误 C4996 ‘fscanf‘: This function or variable may be unsafe.(代码片段

63-Django进阶(路由系统)

Django 进阶篇二