Django Filter Backend

前端 未结 5 1518
面向向阳花
面向向阳花 2021-01-11 18:03

I\'m working with Django rest framework API, I am trying to make a filter by first_name or by last_name or by both of them. This is my ContactViewSet.py :

5条回答
  •  长情又很酷
    2021-01-11 18:49

    I solved my problem by modifying my class ContactFilter like this:

    import django_filters
    from .models import Contact
    
    class ContactFilter(django_filters.FilterSet):
       class Meta:
            model = Contact
            fields = {
                'first_name': ['startswith'],
                'last_name': ['startswith'],
            }
            together = ['first_name', 'last_name']
    

    And in my view I just had to do this :

    class ContactViewSet(viewsets.ModelViewSet):
        queryset = Contact.objects.all()
        serializer_class = ContactSerializer
        filter_class = ContactFilter
    

    My request url looks like :

    http://localhost:8000/api/v1/contact/?first_name__contains=Cl&last_name__contains=Tes
    

    But I still wonder if I can have something like this in Django

    http://localhost:8000/api/v1/contacts/?first_name=Cl**&last_name=Tes**
    

提交回复
热议问题