A review of Django database operations

Source: Internet
Author: User

1. Database operation
-Single Table operation
-All
-Filter
Models.tb.objects.filter (id=123)

DIC = {' id ': 123, ' AGE__GT ': 3}
Models.tb.objects.filter (**dic)
-Count
-Order_by
...
-one-to-many
# ID Name
1 Hebei
2 Guangdong
3 Shandong
Class Province (models. Model):
Name = models. Charfield (max_length=32,)
# nid = Models. Intergar (unique=true) # Unique

# ID Name Pro
1 Dongguan 2
2 Shenzhen 2
3 Huizhou 2
4 Heyuan 2
5 Taian 3
6 Qingdao 3
7 Jinan 3
8 Zhangjiakou 1
9 Xingtai 1
Class city (models. Model):
Name = models. Charfield (MAX_LENGTH=32)
Pro = models. ForeignKey ("Province", to_filed= ' id ')
The default is the ID of the associated province, so we can associate the specified field of the province table, and if the associated table has a specified field, the specified field of the table must be set to unique unique=true)




1, forward lookup, through the table to find ForeignKey
result = models. City.objects.all () object
Result[0].pro.name

Models. City.objects.all (). VALUES (' id ', ' name ', ' pro_id ', ' pro__id ', ' pro__name ') dictionary
Models. City.objects.all (). Values_list (' id ', ' name ', ' pro_id ', ' pro__id ', ' pro__name ') list

2, reverse lookup, through the table without ForeignKey find

result = Models.a3 = Pro.city_set.all (). Objects.values (' id ', ' name ', ' City__name ')

result = models. Province.objects.all ()
RESULT[0] # get Hebei
Result[0].city_set.all () # Get all the cities under Hebei Zhangjiakou, Xingtai

For pro in Result:
A1 = Pro.id
A2 = Pro.name
A3 = Pro.city_set.all ()
All the municipalities of a province are obtained here

A3 = Pro.city_set.filter (ID_LT)
City_set can be used after the Filter,all and other methods


Print (A1,A2,A3)
=====> Many-to-many constructs even on a one-to-many basis

A review of Django database operations

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.