MattBroach / DjangoRestMultipleModels

View (and mixin) for serializing multiple models or querysets in Django Rest Framework
MIT License
549 stars 67 forks source link

Does DjangoRestMultipleModels support POST, PUT, PATCH, and DELETE? #45

Closed danlynkew closed 5 years ago

danlynkew commented 5 years ago

That is, can I create a new "Dog" by POSTing to /animals/ ?

Or does the package only serialize and list multiple models in response to a GET request?

MattBroach commented 5 years ago

The FlatMultipleModelAPIView and ObjectMultipleModelAPIView, out of the box, only support GET requests. In a large part this is because, since the whole point of the multiple model API views is to serialize multiple object types simultaneous, it's ambiguous as to what a POST or a PUT would mean in this context. If your /animals/ view had both a "Dog" and a "Cat", how would it determine where your POST was supposed to make a new Dog, Cat, or both?

If you wanted to add that functionality, and had a very clear idea of what you'd want the semantics to be, you could create your own view using one of the multiple model mixins and rest_framework's own builtin mixins, such as:

from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin
from drf_multiple_model.mixins import ObjectMultipleModelMixin

from animals.models import Dog, Cat
from animals.serializers import DogSerializer, CatSerializer

class AnimalPostAndGetView(CreateModelMixin, ObjectMultipleModelMixin, GenericAPIView):
     # the `querylist` field will be used during GET requests
     querylist = [
         {'queryset': Dog.objects.all(), 'serializer': DogSerializer},
         {'queryset': Cat.objects.all(), 'serializer': CatSerializer},
     ]
     # the `queryset` and `serializer_class` fields will be used for POST request to create a `Dog`
     queryset = Dog.objects.all()
     serializer_class = DogSerializer

So that would definitely work for using GET to get multiple models and using POST for creating a Dog object, although it's a little awkward to have both the queryset AND querylist attributes, but they are required for the different interfaces for the different mixins. If, on the other hand, if you wanted create something that could POST to create either a Dog or a Cat, you'd have to create that logic for yourself.