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