Home > Software engineering >  How to make simple filtration with django-filter
How to make simple filtration with django-filter

Time:11-01

I faced with a problem. I have a simple drf project with car-entrance permits application.

views.py `

class PermitViewSet(ModelViewSet):
    queryset = Permit.objects.filter()
    serializer_class = PermitSerializer
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['car_number']

serializers.py `

class PermitSerializer(serializers.ModelSerializer):
    class Meta:
        model = Permit
        fields = ['car_number', 'is_active']

models.py `

class Permit(models.Model):
    car_number = models.CharField(max_length=15)
    customer = models.ForeignKey(User, on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)

urls.py

router = SimpleRouter()

router.register(r'permit', PermitViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    
]


urlpatterns  = router.urls

`

i type in my browser http://127.0.0.1:8000/api/v1/permits/?car_number=555

and i recieve full list of cars `

[{"car_number":"555","is_active":true},{"car_number":"666","is_active":true},{"car_number":"777","is_active":true}]

` It doesn't work, what's the problem?

CodePudding user response:

You specify the fields with the filterset_fields attribute [drf-doc], not the filter_fields attribute:

class PermitViewSet(ModelViewSet):
    queryset = Permit.objects.all()
    serializer_class = PermitSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['car_number']

CodePudding user response:

First of all, I think it's might be better to change CharField of 'car_number' in your model to IntegerField

In the case of API, I recommend the use of third party app like Django-filter For example,

pip install django-filter

settings.py

INSTALLED_APPS=[
   .....
   'django-filters'
]
REST_FRAMEWORK={'django_filters.rest_framework.DjangoFilterBackend'}

views.py

from django-filters import rest_framework as filters 

class AAA(filters.FliterSet):
  car_number=filtersNumberFilter(field_name='car_number', lookup_expr=555)
  class Meta:
      model=.....
      fields=[...]

class BBB(ModelViewSet):
  ........
  filter_class=AAA
  • Related