Python Learning 20th Day Django Knowledge

Source: Internet
Author: User

One, Django models

1,django ORM How to get back data in a total of three

(1) V1 = models. Business.objects.all ()

The return value is the Queryset type, and the inner element is the object

[Obj (Id,caption,code), obj (id,caption,code), obj (Id,caption,code)]

(2) v2 = models. Business.objects.all.values (' id ', ' caption ')

The return value is the Queryset type, and the inner element is a dictionary

[{' id ': 1, ' caption ': ' Operations '},{' ID ': 2, ' caption ': ' marketing department '},...]

(3) v3 = models. Business.objects.all.values_list (' id ', ' caption ')

Return value is Queryset type, inner element is tuple

{(1, operation and Maintenance), (2, development)}

2,models. Business.objects.get (id=1) Gets the value of an object, if it does not exist directly error

3,models. Business.objects.filter (id=1). First () Gets the value of an object that does not exist returns none

4, host management project code, views.py value as Object form

(1) Models code from DJANGO.DB import models# Create your models here.# class Foo (models. Model): # NAME = models. Charfield (Max_length=1) class business (models. Model): # ID caption = models. Charfield (max_length=32) code = models. Charfield (max_length=32,null=true,default= "SA") # FK = models. ForeignKey (' Foo ') class Host (models. Model): Nid = Models. Autofield (PRIMARY_KEY=TRUE) hostname = models. Charfield (max_length=32,db_index=true) IP = models. Genericipaddressfield (protocol= "IPv4", db_index=true) port = models. Integerfield () b = models. ForeignKey (to= "Business", to_field= ' id ') #b an object that encapsulates a row of data within a business table (2) views.py Code def host (Reque ST): v1 = models. Host.objects.filter (nid__gt=0) #相当于models. Host.objects.all () for row in V1:print (Row.nid,row.hostname,row.ip,row.port,row.b_id,row.b.caption,row.b.code, row.b.id,sep= ' \ t ') return HttpResponse (Request, ' host.html ', {' V1 ': v1}) (3) Templates host.html <tAble border= "1" > <thead> <tr> <th> serial number </th> <t H> host name </th> <th>IP</th> <th> Port </th> <th&gt                 Line of Business name </th> <th> operations </th> </tr> </thead> <tbody>                        {% for row in v1%} <tr hid= "{{Row.nid}}" Bid= "{{row.b_id}}" >                        #隐藏掉Host的nid列和Business的id列 <td>{{Forloop.counter}}</td>                        <td>{{row.hostname}}</td> <td>{{row.ip}}</td>                        <td>{{row.port}}</td> <td>{{row.b.caption}}</td>                        <td> <a class= "edit" > Edit </a>|<a class= "Delete" > Delete </a> </td>                   </tr> {% endfor%} </tbody> </table> 

5, host management, views.py value for dictionary form

(1) views.py Code def Host (Request):     v2 = models. Host.objects.filter (nid__gt=0). VALUES (' nid ', ' hostname ', ' b_id ', ' b__caption ')  #b跨表查询为__双下划下     # QuerySet: [{}]     # Print (v2)     # for row in V2:     #     print (row[' nid '],row[' hostname '],row[' b_id ') '],row[' b__caption ')     return render (Request, ' host.html ', {' V2 ': V2}) (2) Templates  HTML code    

6, host management, views.py value for the form of tuples

(1) views.py Code def Host (Request):    V3 = models. Host.objects.filter (nid__gt=0). Values_list (' nid ', ' hostname ', ' b_id ', ' b__caption ')    # QuerySet: [()]    # Print (v2)     return render (Request, ' host.html ', {' V3 ': v3}) (2) Templates  HTML code    

Special values for the For loop in 7,templates

(1) Forloop.counter cycle counter (counting starting from 1, can be used as an ordinal column)

(2) Forloop.counter0 cycle counter (counting starting from 0)

(3) Forloop.revcounter cycle counter (reverse counting from 1)

(4) Forloop.revcounter0 cycle counter (reverse counting from 0)

(5) Whether Forloop.last is the last Forloop.first is the first

8, Ajax content

(1) Ajax Frontend code example

$.ajax ({url: '/host ',                                        #提交的urltype: ' POST ',                                        #提交的方式data: {' K1 ': 123, ' K2 ': ' Root '},                      #提交的数据success: function (data) {                             #后台返回数据后, the triggered function//data is the server-side returned string    var obj = json.parse (data);}})

(2) Ajax views.py need to use HttpResponse ("string") when returning

If the value obtained by view.py is a dictionary, you need to use Json.dumps ("dictionary"), and return the return HttpResponse (Json.dumps ("dictionary")

The front end receives the string and deserializes it into an object in JavaScript with var obj=json.parse (data)

The front end transforms the object into a string, using Json.stringify () in JavaScript, such as list=[1,2,3,4], to convert the list to a string J Son.stringify (list)

(3) Ajax backend return available HttpResponse () and render (contains only strings)

(4) Ajax gets all the values in the form data:$ (' #add_form '). Serialize ()

9,models Many-to-many custom relationships table definition methods

Class Host (models. Model): Nid = Models. Autofield (PRIMARY_KEY=TRUE) hostname = models. Charfield (max_length=32,db_index=true) IP = models. Genericipaddressfield (protocol= "IPv4", db_index=true) port = models. Integerfield () b = models. ForeignKey (to= "Business", to_field= ' ID ') class application (models. Model): name = models. Charfield (MAX_LENGTH=32) class Hosttoapp (models. Model): Hobj = models. ForeignKey (to= ' Host ', to_field= ' nid ')                   #Host表中的一行对象aobj = models. ForeignKey (to= ' application ', to_field= ' id ')             #Application表中的一行对象

10,models automatic creation of many-to-many relationship tables

(1) models.py code example

Class Host (models. Model): Nid = Models. Autofield (PRIMARY_KEY=TRUE) hostname = models. Charfield (max_length=32,db_index=true) IP = models. Genericipaddressfield (protocol= "IPv4", db_index=true) port = models. Integerfield () b = models. ForeignKey (to= "Business", to_field= ' ID ') class application (models. Model): name = models. Charfield (max_length=32) R = models. Manytomanyfield ("Host")                        #默认最多只能创建两列的关联关系

(2) Data manipulation

1, obj =application.objects.get (id=1)

The Obj object contains two content, OBJ.NAME,OBJ.R,

If you want to add a value of Obj.r.add (1) to add a 1 to the third table, corresponding to 1, that is, the host ID is 1,application ID 1

Obj.r.add (2) indicates an increase of 1 in the third table, corresponding to 2, that is, the host ID is 2,application ID 1

Additionally an increase can be passed to a list [1,2,3,4] Obj.r.add (*[1,2,3,4]) to add a application ID for the 1,host ID of 1,2,3,4 that is 1-1,1-2,1-3,1-4

2, Obj.r.remove (1), delete 1-1

Obj.r.remove (*[1,2,3]), deleting 1-1,1-2,1-3

Obj.r.remove (2,4), deleting 1-2,1-4

3,obj.r.clear () Clears all associated data from application to 1

4,obj.r.set ([3,5,7]) indicates that the setting application is 1, all associations are only 3,5,7, that is, only 1-3,1-5,1-7

5,obj.r.all () Gets all the host object "list" of the associated application ID 1

11,ajax content Supplement

(1)

$.ajax ({url: '/host ',                                        #提交的urltype: ' POST ',                                        #提交的方式data: {' K1 ': 123, ' K2 ': ' Root '},                      #提交的数据        dataType: ' JSON ',                                     #将后台返回的数据转化为json对象, no longer required json.parse conversion success:function (obj) {                              #后台返回obj对象, triggered function//data is the server-side returned string}})

(2) List of data to be sent back to the backend

$.ajax ({url: '/host ',                                        #提交的urltype: ' POST ',                                        #提交的方式data: {' K1 ': 123, ' host_list ': [All-in-all]},                      #提交的数据        DataType: ' JSON ',                                     #将后台返回的数据转化为json对象, no longer required json.parse conversion        traditional:true,                                       #将host_list列表转为字符串success: function (obj) {                              #后台返回obj对象, the trigger//data is the server-side returned string}}) #views. PY gets the request. Post.getlist (' host_list ')                        #可以获取host_list列表中的所有值

    

Python Learning 20th Day Django Knowledge

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.