Django Web Supplement

Source: Internet
Author: User

I. Contents of today

One, Django orm even table operation

Q,f

Second, form form verification

Object oriented

Regular

Third, the session framework

Object oriented

Cookies

Toanado extension

Two, Django ORM one-to-many data creation and lookup

1. Data creation

For tables that are not associated with a foreign key, you can directly create

For tables associated with foreign keys, you can create data in two ways:

Mode A: Add data by ID

def user_info (request): DiC= {'username':'xx',' Age': the,'user_type_id':1} #通过id添加数据 models. UserInfo.objects.create (**dic) Result=models. UserInfo.objects.all () forIteminchresult:print item.username,item.age,item.user_type.caption #对象访问属性

Mode B:

DIC = {'username':'Alex',' Age': the,'User_type': Models. Usertype.objects.Get(id=1)} models. UserInfo.objects.create (**dic) Result=models. UserInfo.objects.all () forIteminchresult:print item.username,item.age,item.user_type.caption #对象访问属性

2, the data forward lookup

For data that is not associated with a foreign key, look directly in the following way

Models. UserInfo.objects.filter (username= ' Alex ') #不是外键关联的数据

For the data associated with the foreign key, the "__" double underlines the following way to find:

    result = models. UserInfo.objects.filter (user_type__caption="CEO")    #通过外键关联的数据的查找方式      for inch Result:        print item.username,item.age,item.user_type.caption    return HttpResponse ( " OK ")

3. Data Reverse Lookup

First look at the table structure

 from django.db Import Models class usertype (models. Model):    = models. Charfield (max_length=)class  UserInfo (models. Model):    = models. ForeignKey (usertype)    #在创建数据的时候, need to be down to create a select user type, in which case    a one-to-many = models is required . Charfield (max_length=)    = models. Integerfield ()

You can see that usertype is a table associated with a userinfo table through a foreign key, so finding data in userinfo tables by usertype is called reverse lookup

There is now a requirement to obtain the user type of a person and to calculate the number of users of that user type

Analysis: The user type exists in the Usertype table, but the user name exists in the UserInfo table, you can get the user type of the specified user in the Usertype table directly through the forward lookup, because the user name is cross-table and needs to be represented by double underscore

By creating a user type object in the Usertype table, the _set Inverse Association userinfo table is used to find the number of corresponding users;

    User_type_obj =models. Usertype.objects. Get (userinfo__username='Alex')    #对象 (usertype)    print user_type_obj.caption                 #实例    Print User_type_obj.userinfo_set.all (). Count ()    return HttpResponse ("  OK")

In lifting a chestnut:

In the previous BBS project, if you want to get the number of likes of all articles, how to do it? First, look at the following table structure:

classMyUser (models. Model): Username= Models. Charfield (max_length= +) Password= Models. Charfield (max_length= -) def __unicode__ (self):returnSelf.usernameclassNEWs (models. Model): Title= Models. Charfield (max_length= +) Content= Models. Charfield (max_length= +) def __unicode__ (self):returnSelf.titleclassFavor (models. Model): User_obj=models. ForeignKey (MyUser) new_obj=models. ForeignKey (NEWs) def __unicode__ (self):return "%s to%s"% (Self.user_obj.username,self.new_obj.title)

From the above table structure can be seen, like the table favor through the foreign Key association news and MyUser table, through the news table, get the number of data in the favor table, need to be obtained by reverse lookup, as follows:

    New_list = models. NEWs.objects.all ()    #获取文章的实例     for in   new_list:        print item.title         " ############# "         print item.content        print Item.favor_set.all (). Count ()    #反向查找

Next demand changes, ask to find Dali liked the number of articles;

Analysis: If you start searching from the news table, you need to query news-->favor-->myuser across the table by double underscores until you find the condition Username=dali.

    New_list = models. News.objects. Filter (favor__user_obj__username='dali')  #filter返回的是列表, did not return as []
for in new_list: print item.title "############# " print item.content print Item.favor_set.all (). Count ()

Note: When creating an object, if it is a conditional query, you need to use the filter and get, note that the difference is: Get returns a dictionary, without looping, through. Gets the required field directly, and if the return value is not unique or empty, an error is made, and for filter, the list is returned. The return value is not unique and does not give an error, and if the value is null, return [], pay attention to get the field, need to loop; All () returns the list as well;

4, OK, now the two ways to find the data are summarized as follows:

Forward Lookup: Filter (cross-table) objects __ fields across tables

Line. objects. Fields across tables

Reverse Lookup: Filter (cross-table) automatically creates an object with the same table name __ fields across tables

Line. Automatically creates an object with the same table name __set.filter ()/all () [0:1]

Ii. Django ORM Many-to-most data creation and lookup

1, forward to add data

First look at the table structure, for many-to-many, the foreign key associated field hostadmin/host can be placed in any table, but this time need to pay attention to forward and reverse can

class Host (models. Model):    = models. Charfield (max_length=)    = models. Integerfield ()class  hostadmin (models. Model):    = models. Charfield (max_length=)    = models. Charfield (max_length=)    host=models. Manytomanyfield (Host)

Next create the data

Models. Host.objects.create (hostname='C1', port= the) models. Host.objects.create (hostname='C2', port= the) models. Host.objects.create (hostname='C3', port= the) models. HostAdmin.objects.create (username='Alex', email='[email protected]') models. HostAdmin.objects.create (username='Root', email='[email protected]') models. HostAdmin.objects.create (username='Dali', email='[email protected]') models. HostAdmin.objects.create (username='Haojie', email='[email protected]')

The data contents are as follows:

Now you need to create the data in the associated table host table as follows:

Forward creating data

    Admin_obj=models. Hostadmin.objects. Get (username='dali')    #创建username的对象    host_list=models. Host.objects.filter (id__lt=3)     #创建主机id小于3的对象    admin_obj.host.add (*host_list)                      #添加数据     return HttpResponse ("OK")

2. Reverse Data addition

    Host_obj =models. Host.objects. Get (id=3)         = Models. HostAdmin.objects.filter (id__gt=1)   #id值大于1    host_obj.hostadmin_set.add (*admin_list)             #反向数据添加

Summary: Whether you are adding or reversing data to the data, depending on which table the many-to-many associated fields exist in, the same point is that a fixed value in a table has multiple values for the other table;

3. Django Many-to-many custom third relationship table

The following three tables, for the third table, the first table and the second table is the foreign key of the third table, the fields in its table are all related to the other tables through the foreign key, then can I have another field in the third table? The answer is yes.

See below: Django Many-to-many ORM create a third custom relational table, implemented by through parameters;

classHost1 (models. Model): hostname= Models. Charfield (max_length= +) Port=models. Integerfield ()classHostAdmin1 (models. Model): Username= Models. Charfield (max_length= +) Email= Models. Charfield (max_length= +) Host=models. Manytomanyfield (host1,through='hostrelation')classHostrelation (models. Model): C1=models. ForeignKey (Host1) C2=models. ForeignKey (HostAdmin1)
#可以在下面继续增加其他的字段, if you want.

Is that a problem? How does the data be written when the third table is customized?

In fact, at this point in the third table to write data, is the value of the ID written, there are two ways: through the query object writing and direct writing, see below

#通过查询对象写入, database operations need to be performed after querying    
Models. HostRelation.objects.create ( C1=models. Host1.objects. Get (id=1), C2=models. Hostadmin1.objects. Get (id=2) )
#直接写入, no queries, recommended way;    
Models. HostRelation.objects.create ( #0次数据库查询, one database insert c1_id=2, c2_id=1 , )

4, Django ORM more than the majority of the two ways to query

Mode 1:

    #正向查     =models. Hostadmin.objects. Get (id=1)    admin_obj.host.all ()    #反向查     =models. Host.objects. Get (id=1)    host_obj.hostadmin_set.all ()

Mode 2: Query by a custom third table (recommended)

    Relation_list = models. HostRelation.objects.all ()    for in  relation_list:        print Item.c1.hostname        Print item. C2.username    = models. HostRelation.objects.filter (c2__username='Alex')    for inch relation_list1:        print item.c1.hostname        print item. C2.username

Comparison: The second way to query all the data, and the number of operations of the database is small, and easy to expand (Add new fields) recommended to use;

Django Web Supplement

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.