Django model high find
Model
class Employees(models.Model):
emp_no = models.IntegerField(primary_key=True)
birth_date = models.DateField()
first_name = models.CharField(max_length=14)
last_name = models.CharField(max_length=16)
gender = models.CharField(max_length=1)
hire_date = models.DateField()
class Meta:
managed = False
db_table = 'employees'
View
group_by
**importance ** if you want to group in Django, You must use annotate with order_by。
重要,如果你想在Django进行分组,你必须annotate和order_by同时使用。
Employees.objects.annotate(sum_birth_date=Max('birth_date')).order_by("birth_date").all()
generate sql
SELECT `employees`.`emp_no`, `employees`.`birth_date`, `employees`.`first_name`, `employees`.`last_name`, `employees`.`gender`, `employees`.`hire_date`, MAX(`employees`.`birth_date`) AS `sum_birth_date` FROM `employees` GROUP BY `employees`.`emp_no` ORDER BY `employees`.`birth_date` ASC
order_by
if you want to order_by in django. You can use order_by.
employs = Employees.objects.order_by('birth_date').all()
generate sql
SELECT `employees`.`emp_no`, `employees`.`birth_date`, `employees`.`first_name`, `employees`.`last_name`, `employees`.`gender`, `employees`.`hire_date` FROM `employees` ORDER BY `employees`.`birth_date` ASC
indicates to query certain fields(只查询某些字段)
if you query all the fields。this is a time-consuming operation. (如果你想查询所有的字段,这是一个耗时的操作)
so we need fields queries. 所以我们需要指定字段查询
values
employs = Employees.objects.values('birth_date').all()
generate sql
SELECT `employees`.`birth_date` FROM `employees`