I have a question regarding using only 1 view or end-point to make multiple requests. We have a url defined as
path('ap/', APIndex.as_view())
where we'd like to both get all our AP models as well as create a new one.
We have checked the link here,
mostly the answer where Mohammad Masoumi mentioned the get_serializer_class
method and the use of generic views.
This has not worked however as we get the following error message when doing a simple GET request on the above URL.
AttributeError at /ap/
'APIndex' object has no attribute 'action'
This occurs in our views_ap.py file in the get_serializer_class
method. I have not been able neither to print the self to see what object I had in there.
You'll find below our views_ap.py
and serializers_ap.py
:
views_ap.py
:
from rest_framework import generics
from ..models.model_ap import AP
from ..serializers.serializers_ap import *
from ..serializers.serializers_user import *
class APIndex(generics.ListCreateAPIView):
"""List all ap, or create a new ap."""
# serializer_classes = {
# 'get': APIndexSerializer,
# 'post': UserIDSerializer,
# # ... other actions
# }
queryset = AP.objects.all().order_by('id')
# mapping serializer into the action
serializer_classes = {
'list': APIndexSerializer,
'create': APCreateSerializer
}
default_serializer_class = APIndexSerializer # Default serializer
def get_serializer_class(self):
print(self)
return self.serializer_classes.get(self.action, self.default_serializer_class)
serializers_ap.py
:
from rest_framework import serializers
from ..models.model_ap import AP
from .serializers_user import *
class APIndexSerializer(serializers.ModelSerializer):
user = UserIndexSerializer()
class Meta:
model = AP
fields = [
'id',
'user',
'name'
]
def to_representation(self, obj):
self.fields['user'] = UserIndexSerializer()
return super(APIndexSerializer, self).to_representation(obj)
class APCreateSerializer(serializers.ModelSerializer):
# user = UserIDSerializer()
class Meta:
model = AP
fields = [
'user',
'name'
]
def create(self, validated_data):
ap = AP.objects.create(**validated_data)
return ap
Being new to Django I actually have a few questions, to better understand it:
- Is it possible to detect the request type using Generic views (GET, POST etc.)?
- If yes, then how to do so?
- I am correct in understanding that the
self
object in theget_serializer_class
method actually is the request?
Thanks!