Views.py -
@api_view(['GET']) def view_items(request): if request.query_params: items = Item.objects.filter(**request.query_param.dict()) #error line else: items=Item.objects.all() serializer=ItemSerializer(items,many=True) if items: return Response(serializer.data) else: return Response(status=status.HTTP_404_NOT_FOUND)
CodePudding user response:
The **request.query_param
should be changed into **request.query_params
.
CodePudding user response:
Let's say you want to filter by name.
@api_view(['GET'])
def view_items(request):
name = request.query_params.get("name", None)
if name:
items = Item.objects.filter(name=name)
I would suggest you to use django-filters, that's a better way to structure your code.
Create Item app
urls.py
app_name = "app-name"
router = SimpleRouter()
router.register("items", ItemViewSet, basename="item")
views.py
class ItemViewSet(views.ModelViewSet):
queryset = Item.objects.all()
serializer_class = ItemSerializer
filterset_class = ItemFilterSet
serializers.py
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ("id", "name", "label")
filters.py
from django_filters import rest_framework as filters
class ItemFilterSet(filters.FilterSet):
class Meta:
model = Item
fields = ("name", "label")
Good luck!
(A tip for the next time, please format the code by adding inside ```)