Django 自学笔记兼学习教程第5章第2节——进阶查询——Queryset
点击查看教程总目录
Queryset相关内容其实蛮多的,本文只介绍一些常用的,详细的推荐查询官方文档:queryset-api
0 - 数据示例
为了方便本文后面内容举例,这里先展示下models.py
和数据库表内容,myapp/models.py
在本章第一节,如下:
from django.db import models
class Person(models.Model):
gender = (
('male', '男'),
('female', '女'),
)
name = models.CharField(max_length=60)
sex = models.CharField(max_length=32, choices=gender, default='男')
age = models.IntegerField()
>>> from myapp.models import Person
>>> info_list = [
["Li Hua", "male", 20],
["Big Shuang", "male", 24],
["Xiao Hong", "female", 21],
["Xiao Hua", "female", 19],
["Ellen", "female", 20],
["Zhang Sirui", "female", 22],
["Alex", "male", 23],
["Zhao Wen", "female", 24],
["Sun Wu", "male", 18],
["Qian Kong", "male", 22],
]
>>> for info in info_list:
name, sex, age = info
pi = Person(name=name, sex=sex, age=age)
pi.save()
>>> for info in info_list:
name, sex, age = info
print("|{ ^10}|||%s")
数据库表Person如下
id | name | sex | age |
---|---|---|---|
0 | Li Hua | male | 20 |
1 | Big Shuang | male | 24 |
2 | Xiao Hong | female | 21 |
3 | Xiao Hua | female | 19 |
4 | Ellen | female | 20 |
5 | Zhang Sirui | female | 22 |
6 | Alex | male | 23 |
7 | Zhao Wen | female | 24 |
8 | Sun Wu | male | 18 |
9 | Qian Kong | male | 22 |
1 - 查询方法
个人最常用的查询方法是filter
,可以简单理解为按条件查找(筛选),该方法返回一个Queryset
对象
-
字段查找(Field lookups)
-
quertset 基础操作
-
操作符