Django queries the last data of each month

Query the last data of each month

In this example, we will demonstrate how to use Django to query Bookthe last data of each month named "Zhang San" in the data table.

data model

First, we define a Bookmodel 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, mobileand create_atfields.

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:

  1. Use the annotateand ExtractMonthfunction to calculate the month value for each record and store the result in montha field.
  2. Use valuesmethod to get monththe unique value of a field.
  3. Calculate the maximum value using annotatethe and function and store the result in a field.Maxcreate_atmax_create_at
  4. Use valuesthe method to get the unique value of the field again max_create_at.
  5. Use subquery filterto get the last data of each month in clause.

Now, querysetthere will be an object containing the last piece of data for each month QuerySetand you can perform further operations or use this object as needed.

Guess you like

Origin blog.csdn.net/weixin_44649870/article/details/131701579