Query the last data of each month
In this example, we will demonstrate how to use Django to query Book
the last data of each month named "Zhang San" in the data table.
data model
First, we define a Book
model with the following fields:
from django.db import models
class Book(models.Model):
name = models.CharField(max_length=64, verbose_name="姓名", default=None, null=True)
id_no = models.CharField(max_length=24, verbose_name="身份证号", default=None, null=True)
mobile = models.CharField(max_length=11, verbose_name="手机号", default=None, null=True)
create_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', db_index=True)
The model contains name
, id_no
, mobile
and create_at
fields.
Query the last data of each month
Now, we will show how to query the last data of each month:
from django.db.models import Max, Subquery
from django.db.models.functions import ExtractMonth
last_per_month = (
Book.objects.filter(name="张三")
.annotate(month=ExtractMonth('create_at'))
.values('month')
.annotate(max_create_at=Max('create_at'))
.values('max_create_at')
)
queryset = Book.objects.filter(
name="张三",
create_at__in=Subquery(last_per_month)
)
In this example we follow these steps:
- Use the
annotate
andExtractMonth
function to calculate the month value for each record and store the result inmonth
a field. - Use
values
method to getmonth
the unique value of a field. - Calculate the maximum value using
annotate
the and function and store the result in a field.Max
create_at
max_create_at
- Use
values
the method to get the unique value of the field againmax_create_at
. - Use subquery
filter
to get the last data of each month in clause.
Now, queryset
there will be an object containing the last piece of data for each month QuerySet
and you can perform further operations or use this object as needed.