[PYTHON] [Django Rest Framework] Customize the filter function using Django-Filter

Overview

This article walks you through the steps of a beginner developing a coupon distribution service for the iPhone with a RESTful API and swift. It is a very detour implementation because it was implemented while examining the technical elements one by one.

Matches the parameters of a field specified using Generic Filtering in the previous Django Rest Framework to set a filter to respond only to specific data (https://qiita.com/Ajyarimochi/items/7e22de20292ca57ea8dc). I was able to filter the data. However, with this method, it is not possible to filter the specified parameters under the conditions of "greater than or equal to" and "less than or equal to".

Therefore, this time, we will implement a filter function that determines the expiration date based on conditions such as "before" and "after" for the date.

If you haven't installed Django-Filter, please install it by referring to Previous article.

reference

environment

Mac OS 10.15 VSCode 1.39.2 pipenv 2018.11.26 Python 3.7.4 Django 2.2.6

procedure

Create a FilterSet class in views.py

Create an original filter set by inheriting the FilterSet class of django_filter. First, add a process to import the FilterSet class.


from django_filters import rest_framework as filters

Then implement the original filter set before the ViewSet class.


class CustomFilter(filters.FilterSet):
    #Filter definition
    deadline = filters.DateFilter(field_name='deadline', lookup_expr='gte')

    class Meta:
        model = Coupon
        fields = ['deadline'] #Enumerate defined filters

The following part is the filter setting. This time I will use DateFilter, but there are many other filters such as string filters and numerical filters. See Official Documentation for more information!


deadline = filters.DateFilter(field_name='deadline', lookup_expr='gte')

** Supplement ** The above field_name = ‘’ specifies the name of the model field you want to filter. If you do not specify a name here, the name of the filter definition (deadline part in the above code) will be treated as the name of the model field to be filtered.

(Field_name is specified in the sample code, but it is not actually necessary if it is the same as the name of the filter definition.)

The parameter name when making a request will be the name of the filter definition. In other words, ** if you want the parameter name to be different from the model field name when requesting, you need to set field_name **.

Set the model name of the filtered data in model = ~ below. Fields = [~] lists the names of the filter definitions.


    class Meta:
        model = Coupon
        fields = ['deadline']

Added processing to call FilterSet in existing ViewSet

Just call the filter class implemented above as filter_class.


filter_class = CustomFilter

Try out

Estimated 5 minutes → 5 minutes

Compares the difference in the data that can be obtained when and when deadline, which indicates the expiration date of the coupon, is not specified as the request parameter.

** If the parameter deadline is not specified **

request

curl -X GET http://127.0.0.1:8000/api/coupons/

response

[{"id": 1, "code": "0001", "benefit": "1,000 yen discount from payment", "explanation": "Limited to customers using 5,000 yen or more. Cannot be used with other coupons. "," store ":" All stores "," start ":" 2019-10-01 "," deadline ":" 2019-12-31 "," status ": true}, {" id ": 2," code ":" 0002 "," benefit ":" 10% off payment! "," explanation ":" Cannot be combined with other coupons "," store ":" Yurakucho store "," start ":" 2019-10 -01 "," deadline ":" 2019-12-31 "," status ": true}, {"id ": 3," code ":" 0003 "," benefit ":" [Halloween only] Disguise 30% off when you come to the store "," explanation ":" Only for customers who are disguised as 50% or more of the whole body (judgment is the feeling of the staff). Cannot be used with other coupons "," store ":" Kanda store "," start ":" 2019-10-31 "," deadline ":" 2019-10-31 "," status ": true}, {"id ": 4," code ":" 0004 ", "benefit": "[September only] Moon-viewing dumpling service", "explanation": "Given a moon-viewing dumpling to customers who wish! Can be used with other coupons!", "Store": "All stores" , "start": "2019-09-01", "deadline": "2019-09-30", "status": true}, {"id": 5, "code": "0005", "benefit" : "[Rainy days only] 15% off payment", "explanation": "Available only when coupons are delivered. Cannot be combined with other coupons", "store": "All stores", "start" ":" 2019-10-01 "," deadline ":" 2019-12-31 "," status ": false}, {" id ": 6," code ":" 0006 "," benefit ":" [ Sunday only] Cheers Tequila Service "," explanation ":" We will serve Tequila for the number of people. Can be used with other coupons. "," store ":" Kanda Store "," start ":" 2019-11-03 " , "d eadline ":" 2019-12-01 "," status ": true}, {"id ": 7," code ":" 0007 "," benefit ":" 19% discount from your bill "," explanation ": "Limited to December 29th-December 31st. Cannot be used with other coupons "," store ":" Kanda store "," start ":" 2019-12-29 "," deadline ":" 2019-12-31 "," status ": true}]

** When specifying deadline **

Request (Request only coupons with expiration date after December 5th)

curl -X GET http://127.0.0.1:8000/api/coupons/?deadline=2019-12-05

response

[{"id": 1, "code": "0001", "benefit": "1,000 yen discount from payment", "explanation": "Only for customers using 5,000 yen or more. Cannot be used with other coupons. "," store ":" All stores "," start ":" 2019-10-01 "," deadline ":" 2019-12-31 "," status ": true}, {" id ": 2," code ":" 0002 "," benefit ":" 10% off your bill! "," explanation ":" Cannot be combined with other coupons "," store ":" Yurakucho store "," start ":" 2019-10 -01 "," deadline ":" 2019-12-31 "," status ": true}, {"id ": 5," code ":" 0005 "," benefit ":" [Rainy days only] 15% off from checkout "," explanation ":" Only available when coupons are delivered. Cannot be combined with other coupons "," store ":" All stores "," start ":" 2019-10-01 " , "deadline": "2019-12-31", "status": false}, {"id": 7, "code": "0007", "benefit": "19% discount from checkout", "explanation" ":" Limited to December 29th-December 31st. Cannot be used with other coupons "," store ":" Kanda store "," start ":" 2019-12-29 "," deadline ":" 2019 -12-31 "," status ": true}]

I was able to get only coupons that are valid after December 5th.

Next, Implement authentication function

Recommended Posts

[Django Rest Framework] Customize the filter function using Django-Filter
Understand the benefits of the Django Rest Framework
Miscellaneous notes about the Django REST framework
Django REST framework basics
Django Rest Framework Tips
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 1 ~
Create a Todo app with the Django REST framework
When you want to filter with Django REST framework
Implement APIs at explosive speed using Django REST Framework
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 2 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 3 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 4 ~
[CRUD] [Django] Create a CRUD site using the Python framework Django ~ 5 ~
Django REST framework stumbling block
Django REST framework with Vue.js
Login with django rest framework
How to write custom validations in the Django REST Framework
Try using the Python web framework Django (2) --Look at setting.py
How to reset password via API using Django rest framework
Creating an API that returns negative-positive inference results using BERT in the Django REST framework
Implementation of CRUD using REST API with Python + Django Rest framework + igGrid
Precautions when using the urllib.parse.quote function
Install Python framework django using pip
[Django] Use MessagePack with Django REST framework
Create a REST API to operate dynamodb with the Django REST Framework
Try using the Python web framework Django (1)-From installation to server startup
How to build an application from the cloud using the Django web framework
Create RESTful APIs with Django Rest Framework
Try using the web application framework Flask
ng-admin + Django REST framework ready-to-create administration tool
CRUD GET with Nuxt & Django REST Framework ②
CRUD POST with Nuxt & Django REST Framework
CRUD GET with Nuxt & Django REST Framework ①
Django REST Framework + Clean Architecture Design Consideration
Solution when Not Found appears when hitting the Django REST Framework API from the outside
The _authenticate_with_backend function was obsolete in django auth.autenticate
CRUD PUT, DELETE with Nuxt & Django REST Framework
Exclusive release of the django app using ngrok
Try using the Python web framework Tornado Part 1
Django REST framework A little useful to know.
Implement JWT login functionality in Django REST framework
Try using the Python web framework Tornado Part 2
I tried using the image filter of OpenCV
Implementing authentication in Django REST Framework with djoser