0

I have url api/v1/posts/. If we use GET request from that url, we can see all objects. For example:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "url": "http://127.0.0.1:8000/api/v1/posts/11/",
            "id": 12,
            "name": "Sample name",
            "type": "Shirt",
            "collection": "Winter 2020"
        }
    ]
}

We need to create functional -

We can create GET request with filter. In our case, we need to filter "type": "Shirt" and we can see "Collection" with count (count shirts from all collections)

For example:

{
  "collection" : "Winter 2020"
  "result" : [
    {
     "count": 12
    }
  ]
}

Etc... How to create it using Django Rest Framework?

UPD (Added view):

class PostViewSet(LikedMixin, viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    authentication_classes = (TokenAuthentication, SessionAuthentication, )
    filter_backends = (DjangoFilterBackend, )
    filterset_fields = ('name', 'type')


    def perform_create(self, serializer):
        serializer.save(author=self.request.user)
5
  • can you share your view for api/v1/posts/ url pls? Commented Dec 30, 2019 at 16:12
  • @engin_ipek I did update Commented Dec 30, 2019 at 16:53
  • so can you filter your results but cannot return a customized result? Commented Dec 30, 2019 at 16:56
  • @engin_ipek yes. I don't know how to customize filter result. Commented Dec 30, 2019 at 17:09
  • check my answer Commented Dec 30, 2019 at 17:09

1 Answer 1

1

You need to group your Posts by collection and return the count of each collection.

Add this method to your viewset: ( You need to import from django.db.models import Count too.)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        result_list = list(queryset.values('collection').annotate(count=Count('collection')))
        return Response(result_list)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.