This is my code:
models.py
class StoreLists(models.Model):
id = models.AutoField(primary_key=True)
store_name_ = models.CharField(max_length=300,unique=True)
brand = models.CharField(max_length=300)
class Meta:
managed = False
db_table = 'stores'
serializers.py
class StoreListSerializer(serializers.ModelSerializer):
class Meta:
model = StoreLists
fields = "__all__"
views.py
class StoreListView(generics.GenericAPIView): # even tried with viewsets and ListModelView
serializer_class = StoreListSerializer
queryset = StoreLists.objects.all()
filter_backends = (DjangoFilterBackend,)
filterset_fields = ("store_name", "brand")
def get(self, request):
sales = self.filter_queryset(self.get_queryset())
serializer = self.serializer_class(instance=sales, many=True)
return Response(data=serializer.data, status=status.HTTP_200_OK)
urls.py
GET - http://127.0.0.1:8000/api/v1/store_list - getting all data
GET - http://127.0.0.1:8000/api/v1/store_list?brand=samplebrand - getting all data (filter is not working, same with search filter)
Even added django_filters in application and also tried in postman and drf UI but not able to filter.`
CodePudding user response:
When you are using django-filters then you should follow the below steps. I have followed these steps in my project
#settings.py
#...
INSTALLED_APPS = ["django_filters"]
REST_FRAMEWORK["DEFAULT_FILTER_BACKENDS"]=[
"django_filters.rest_framework.DjangoFilterBackend",
"rest_framework.filters.OrderingFilter",
]
#...
#views.py
class TableMetaView(ModelViewSet):
serializer_class = TableMetaSerializer
queryset = TableMeta.objects.all()
renderer_classes = [JSONRenderer]
filterset_class = TableFilter
ordering_fields = ["created_on", "modified_on"]
ordering = ["id", "-modified_on"]
permission_classes = [
UserHasDatasetChangeAccess & IsTableEditable,
]
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
# queryset just for schema generation metadata
return TableMeta.objects.none()
return TableMeta.objects.filter(
dataset=get_object_or_404(DataSet, id=self.request.META.get(DATASET_ID, ""))
)
#TableFilter is imported from custom_filter.py #custom_filter.py
class TableFilter(django_filters.FilterSet):
class Meta:
model = TableMeta
fields = {
"name": ["exact", "icontains"],
"schema_name": ["exact"],
"type": ["exact"],
}
#urls.py
router.register(r"table-meta", TableMetaView, basename="table-meta")