13.Django Database Models&orm Supplementary table operation supplement and other Knowledge Points supplement (ii)

Source: Internet
Author: User
Tags lowercase

A. Foreign key association.

If you say, now there are two tables, a user table, the table contains information about users ' accounts, and a usertype table, which holds the type of user account.

From django.db import Models

Class Usertype (models. Model):

#用户类型表, although the ID field is not created, the ID field is created automatically.

Type = models. Charfield (MAX_LENGTH=32)

Class User (models. Model):

#用户表

Username = models. Charfield (MAX_LENGTH=16)

Password = models. Charfield (max_length=100)

Utype = models. ForeignKey (' usertype ') #创建外键, associated usertype table

#python manage.py makemigrations

#python manage.py Migrate


Second, insert data.

Next, you begin inserting data into the table.

From APP01 import Models

def test (Request):

Models. UserType.objects.create (type= ' admin ')

Models. UserType.objects.create (type= ' user ')

Models. User.objects.create (username= ' admin ', password= ' admin ', utype_id=1)

Models. User.objects.create (username= ' aaa ', password= ' 123 ', utype_id=2)

Models. User.objects.create (username= ' BBB ', password= ' 123 ', utype_id=2)

return HttpResponse (' test ')

#在User用户表中, three rows of data were inserted.

#在业务中可以理解为创建了三个账户, the admin corresponds to the user admin type, the aaa,bbb corresponds to the common user type.


Third, find the data.

1. Cross-table query, forward lookup example.

result = models. User.objects.all () #queryset object Queryset[obj,obj,obj]

For obj in result:

Print (Obj.username,obj.password.obj.utype_id,obj.utype.type)

The output results are as follows:

Admin Admin 1 Admin

AAA 123 2 User

BBB 123 2 User



2. Cross-table query, reverse lookup example.

If there is a need now, find the user through usertype.

Examples are as follows:

obj = models. UserType.objects.all (). First () #取出usertype表中的第一个对象

#print (Obj.user_set.all ()) #返回一个queryset类型的数据, all users of this type will be listed.

#!!!! Attention!! The user in this obj.user_set represents the user table, but in Django, if you need to reverse lookup!! Reverse lookup of the table must be lowercase!! and follow _set!! in the back.


Print (' User type ', obj.id,obj.type)


For row in Obj.user_set.all (): # Obj.user_set.all () takes out all the user types that correspond to the first record in the Usertype table, returns a Queryset type, The contents of the row variable at this time are the user object in Queryset.

Print (Row.username,row.password)


The output results are as follows:

Admin Admin


#也就是说, the reverse lookup method is the table name lowercase plus _set (underscore set).


Reverse lookup can also be filtered by filter:

obj = models. UserType.objects.all ()

For item in obj:

Print (Item.type,item.user_set.filter (username= ' admin '))



3. Some additional notes on Django Orm.

#! When returning a single record, it returns an object with the same name as the table! #

#! When returning multiple records, a Queryset object must be returned! #


About values:queryset[{' username ': ' xxx ', ' password ': ' xxx '}] returns the data as a dictionary.

result = models. User.objects,all (). VALUES (' username ', ' password ') #生成一个queryset数据类型, but this query results only username columns and password columns.

#不过不同的是, the queryset in this is not an object, but a dictionary. queryset[{' username ': ' xxx ', ' password ': ' xxx '}]

For row in result:

Print (row) #获取queryset中的字典数据类型.



About Values_list:

result = models. User.objects,all (). Values_list (' username ', ' password ')

#生成一个queryset数据类型, but this query results only username columns and password columns, except that the Ganso type is stored in Queryset.

# queryset[(' username ', ' xxx '), (' Password ', ' xxx ')]



!! How do I cross tables when using values and values_list?

Double-underline _ _ Cross-table forward lookup:

res = models. User.object.all (). VALUES (' id ', ' username ', ' password ', ' Utype_ _type ') #utype字段通过外键关联了UserType表, Use the Utype field to cross the table to fetch the contents of the Type field in the Usertype table.




Summarize:

If you do not use the values method or the Values_list method, only the object is returned.

Use the values method to return the dictionary.

The Vlaues_list method is used to return the Ganso.



13.Django Database Models&orm Supplementary table operation supplement and other Knowledge Points supplement (ii)

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.