0

I have a project which need to perform different create processes of the same Model.

We can achieved this one by creating multiple ModelViewSet.

class AnimalViewSet(viewsets.ModelViewSet):
    queryset = Animal.objects.all()
    serializer_class = AnimalSerializer

    def create(self, request):
         # just simply create the object...
         pass

Endpoint is POST /api/animal/

class CalvingViewSet(viewsets.ModelViewSet):
    # This is called when an animal has successfully delivered its new born..

    queryset = Animal.objects.all()
    serializer_class = AnimalSerializer

    def create(self, request):
         # define parent animals pregnancy as success
         # and more..
         # finally create the object..
         pass

Endpoint is POST /api/calving/

But i prefer not doing so.

Now it is possible to define multiple create(self, request) in a single ModelViewSet?

class AnimalViewSet(viewsets.ModelViewSet):
    queryset = Animal.objects.all()
    serializer_class = AnimalSerializer

    def create(self, request):
         # just simply create the object...
         pass

    def calving(self, request):
         # create the object..
         # define parent animals pregnancy as success
         # and more..
         pass

By this i can avoid creating another modelviewset for the same Model.

Endpoint for create(self, request): is POST /api/animal/.

The problem is i don't have any idea what is the endpoint for calving(self, request): without using @list_route(methods=['post])

@list_route(methods=['post']) may help but i want to make sure there is another right way to do this.

Shift 'n Tab
  • 8,808
  • 12
  • 73
  • 117
  • 1
    I've responded to your question in the DRF gitter. By definition you can't have multiple create methods (how would anyone know what to call). I think you need to clarify what you are trying to accomplish. If you just want to "switch" behavior, then pass a paramter (in the url, even), detect that, and then call different versions of "create". Its easy to see what it does in the source code. – Andrew Feb 23 '17 at 08:04
  • If you are building REST API then don't think about the models. Think about [resources](http://restful-api-design.readthedocs.io/en/latest/resources.html). I would prefer to create another resource and keep code simple. – Raz Feb 23 '17 at 08:11
  • @AndrewBacker what im trying to accomplished is something like the second modelviewset in my question.. the `calving(self, request):` is what i want to call from the url request without using `@list_route(methods=['post'])` but as like you said it is impossible by definition. – Shift 'n Tab Feb 23 '17 at 08:31
  • @Raz thanks for the link i must study this thing to better understand the concept of RESTFUL API. – Shift 'n Tab Feb 23 '17 at 08:39

0 Answers0