SoFunction
Updated on 2024-10-30

Introduction to DateRangeFilter, a custom time range filter for the django admin admin tool

The django admin admin tool has a lot of good features such as search box, filters, etc. It is easy to code and powerful.

But the conventional time filtering has certain limitations, can only display a certain time node to the current time within a period of filtering results, can not be freely defined time period filtering, I found a plug-in that can achieve this function is to introduce today's DateRangeFilter.

Note: DateRangeFilter only works with Django 1.4 and above.

Plug-in Installation

Use pip or easy_install:

pip install django-daterange-filter

Modify Configuration

Add a configuration entry to INSTALLED_APPS in the following:

INSTALLED_APPS = (
  ...
  'daterange_filter'
)

Add Filter

Let's say you need the fields for normal filtering and sorting by time interval to be written in this way respectively:

class TaskModel():
  ...
  user_name = (u'Username', max_length=128)
  submit_time = (u'Time of submission', auto_now_add=True)
  ...

Then, after introducing the filter plugin:

from daterange_filter.filter import DateRangeFilter

The above point is the most easily overlooked part of the document, so here is a separate list to attract attention.

The complete portion of the DateRangeFilter filter involved in should be written like this:

from daterange_filter.filter import DateRangeFilter
from  import admin
from models import TaskModel

class TaskAdmin():
  list_filter = (
    'user_name',
    ('submit_time', DateRangeFilter), # this is a tuple
    ...
  )

Sign up on the admin page to see the results.

Reference Links:/project/django-daterange-filter/1.1.1/

Additional knowledge:python django orm filtering Time, numeric comparison methods

First of all, let's now say that the rich comparison method in the actual work of the application of the scene, I generally use more is the comparison of time, the number of comparisons, as long as the comparison can be used If I want to create a piece of information, but if the time overlap or conflict will not be able to create a successful, but if the time is not the same as the time, then it will not be able to create a new message.

filter(
      (Q(start_time1__lt=start_time2) & Q(end_time1__gt=end_time2)) |
      Q(start_time1__range=(start_time, end_time)) |
      Q(end_time1__range=(start_time, end_time)))

In the above code, __lt is less than start_time1 is less than start_time2 & and end_time1 is more than end_time2 __gt is more than

'|' means or __range gives a range of time within a range between start_time, and end_time.

The above introduction to this django admin admin tool custom time interval filter DateRangeFilter is all I have to share with you, I hope to be able to give you a reference, and I hope you will support me more.