1👍
Thanks to everyone who suggested django-filter
.
> pip install django-filter
settings.py
INSTALLED_APPS = [
...
'django_filters',
]
views.py
class PersonFilter(django_filters.FilterSet):
class Meta:
model = Person
fields = {'name': ['in', 'regex'],
'child__name': ['in', 'regex'],
'grandparent__name': ['in', 'regex']}
...
person_qs = PersonFilter(request.GET, queryset = Person.objects.all().qs
0👍
For cases like this DRF (Django REST Framework) is a common and very useful solution. Here are the docs about filtering.
An example.
View:
from myapp.models import Person
from myapp.serializers import PersonSerializer
from rest_framework import generics
class PersonList(generics.ListAPIView):
serializer_class = PersonSerializer
filter_backends = [
SearchFilter
]
search_fields = [
'name', 'grandparent__name', 'child__name', # For substring search
'$name', '$grandparent__name', '$child__name' # For regex search
]
And you will also need a Serializer
:
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = '__all__'
That’s all.
- [Answered ]-Nginx, gunicorn, django not passing real IPV6 address
- [Answered ]-Should I be encrypting data in a CloudSQL database?
Source:stackexchange.com