Nesting ViewSet routes in DRF - django

I've created 2 ModelViewSets like so (simplified for demonstration):
class SomeBaseViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = SomeEventSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
return SomeObjects.objects.filter(owner=self.request.user)
def get_serializer_context(self):
context = super(SomeBaseViewSet, self).get_serializer_context()
context.update({
"user": self.request.user,
"some_context_key": False
})
return context
class AdminViewSet(SomeBaseViewSet):
# Added in the HasAdminPermission
permission_classes = (permissions.IsAuthenticated, HasAdminPermission)
# Different queryset filter (overriding `get_queryset` vs setting queryset for standardization)
def get_queryset(self):
return SomeObjects.objects.all()
# The context should have `some_context_key=True`, and `user=request.user`
def get_serializer_context(self):
context = super(AdminViewSet, self).get_serializer_context()
context.update({
"some_context_key": True
})
return context
My router/url config looks like this
router = DefaultRouter()
router.register(r'some_view', SomeBaseViewSet, base_name="some_view")
urlpatterns += [
url(r'^api/', include(router.urls)),
]
If I wanted to route /api/some_view/admin to the AdminViewSet, what's the best way to do that?
Things I've tried:
#list_route on SomeBaseViewSet, but couldn't figure out the "right" way to wire it to my AdminViewSet
Adding url(r'^api/some_view/admin$', AdminViewSet.as_view({"get": "list"})) to my urlpatterns (which sorta works but neuters the ViewSet a bit, and is generally really manual anyway):
Having a dedicated DefaultRouter for the some_view viewset, which I then mount on url(r'^api/some_view/') - again hacky and pedantic to do with a large number of routes
Is there a "right" way to do what I'm trying to accomplish, or should I reach for a different solution to this problem (i.e. a filter or something)?
I've seen libraries like https://github.com/alanjds/drf-nested-routers, but that seems like overkill for my (fairly simple) needs.

Not sure if i've missed something but i've just tested and this works perfectly (the order is important):
router = DefaultRouter()
# this will overrides routes from the line below
router.register(r'some_view/admin', AdminViewSet)
router.register(r'some_view', SomeBaseViewSet)

Define your admin viewset using a list route. These params will allow you to perform a get request, with specified permissions(is authenticated and has admin perms), that extends this class. ie /someview/admin or someotherview/admin
from rest_framework.decorators import list_route
class AdminViewSet(viewset.Viewsets):
#list_route(methods=['get'],
permissions=[permissions.IsAuthenticated, HasAdminPermission],
url_path='admin'
)
def admin(self, request):
# All your custom logic in regards to querysets and serializing
return serialized.data
Then you can extend your any viewset that needs an admin action route.
class SomeBaseViewSet(viewsets.ReadOnlyModelViewSet, AdminViewset):
serializer_class = SomeEventSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
return SomeObjects.objects.filter(owner=self.request.user)
def get_serializer_context(self):
context = super(SomeBaseViewSet, self).get_serializer_context()
context.update({
"user": self.request.user,
"some_context_key": False
})
return context
You want to be careful with this because typically the param after your base route ie /someview/{param}/ is reserved for ID references. Make sure your id reference will not conflict with your detail route.

I think I've found an answer to my own question, but I put a +50 rep bounty on this in case someone wants to chime in (#tom-christie maybe?).
Either way the way that I've solved it for my usecase is by using the #list_route and the AdminViewSet's .as_view() function.
Something like this suffices:
class SomeBaseViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = SomeEventSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
return SomeObjects.objects.filter(owner=self.request.user)
def get_serializer_context(self):
context = super(SomeBaseViewSet, self).get_serializer_context()
context.update({
"user": self.request.user,
"some_context_key": False
})
return context
#list_route()
def admin(self, request):
return AdminViewSet.as_view({"get": "list"})(request)
class AdminViewSet(SomeBaseViewSet):
# Added in the HasAdminPermission
permission_classes = (permissions.IsAuthenticated, HasAdminPermission)
# Different queryset filter (overriding `get_queryset` vs setting queryset for standardization)
def get_queryset(self):
return SomeObjects.objects.all()
# The context should have `some_context_key=True`, and `user=request.user`
def get_serializer_context(self):
context = super(AdminViewSet, self).get_serializer_context()
context.update({
"some_context_key": True
})
return context
And will allow one to have the url's routed accordingly (based on the name of the function), and enforce any extra things you need.

good question. i'd check out DRF's detail_route for this -- this is an idiom i've used successfully in the past to create a one-off type of endpoint that hangs off of a viewset. HTH,
http://www.django-rest-framework.org/api-guide/routers/#extra-link-and-actions

Related

How to use lookup_field along with FilterSet in Django Rest Framework?

I am working on developing an API for a project and it contains a course list page where
All the courses offered by a particular college is listed.
Should support retrieving of a specific course using lookup_field as course_slug.
Supports filtering courses based on some other parameters which I am implementing with the help of Django FilterSet along with filterset_class (filterset_class).
The problem is, once the courses are filtered based on the requirements, the query params is included in the URL as well. Now, I am not able do the retrieve operation on it, as the URL cannot recognize the lookup_field added and mistakes it to a pattern in query params.
ViewSet.py
class CollegeCourseViewSet(viewsets.ReadOnlyModelViewSet):
serializer_class = CourseSerializer
lookup_field = 'slug'
filter_backends = (SearchFilter, DjangoFilterBackend,)
search_fields = ['name']
filterset_class = CourseFilter
def get_queryset(self):
queryset = Course.objects.all()
return queryset.filter(college_courses__college__slug=self.kwargs['college_slug'])
def get_object(self):
obj = super().get_object()
if self.action == 'retrieve':
obj.additional = CollegeCourse.objects.filter(course=obj, college__slug=self.kwargs['college_slug']).first()
return obj
def get_serializer_class(self):
if self.action == 'retrieve':
return CollegeCourseSerializer
return super().get_serializer_class()
filters.py
class CourseFilter(filters.FilterSet):
name = filters.MultipleChoiceFilter(field_name='college_courses__stream__name',
choices=choices("STREAM_NAME_CHOICES"))
category = filters.MultipleChoiceFilter(field_name='college_courses__stream__category',
choices=choices("STREAM_CATEGORY_CHOICES"))
program = filters.MultipleChoiceFilter(field_name='college_courses__stream__program',
choices=choices("STREAM_PROGRAM_CHOICES"))
class Meta:
model = Course
fields = [
'name',
'category',
'program'
]
urls.py
router = routers.DefaultRouter()
router.register(r'courses', CollegeCourseViewSet, basename='college_course')
urlpatterns = [
path('api/college/v1/colleges/<slug:college_slug>/', include(router.urls)),
]
Suppose I filter based on category = Agriculture, I get a list of three courses. Now, I would like to retrieve one of the courses using its slug. But here is the Bad Request message
URL
GET /api/college/v1/colleges/clslug1/courses/?category=Agriculture/crslug2
crslug2 is the slug of the course.
Message
"Select a valid choice. Agriculture/crslug2 is not one of the available choices."
Is there any way to add the lookup_field after the query params?
Thanks in advance.
Okay so answering my own post. Basically everything was fine except that the URL was not RESTful.
The lookup_field must be given before any query params in RESTful apis.
So the correct format is
GET /api/college/v1/colleges/clslug1/courses/crslug2/?category=Agriculture

Url for custom method in django apiview

I am new in Django and I am bit confused in Django apiview for custom method.
In ApiView, How can I create a custom method and How to call from axios.
For example
Here is my View
class TimeSheetAPIView(APIView):
#action(methods=['get'], detail=False)
def getbytsdate(self, request):
return Response({"timesheet":"hello from getbydate"})
def get(self,request,pk=None):
if pk:
timesheet=get_object_or_404(TimeSheet.objects.all(),pk=pk)
serializer = TimeSheetSerializer(timesheet)
return Response({serializer.data})
timesheet=TimeSheet.objects.all()
serializer = TimeSheetSerializer(timesheet,many=True)
return Response({"timesheet":serializer.data})
Here is my URL=>
url(r'^timesheets_ts/(?P<pk>\d+)/$', TimeSheetAPIView.as_view()),
url(r'^timesheets_ts/', TimeSheetAPIView.as_view()),
Normally my url would be like=>
api/timesheet_ts/
this one will get all of my records.
So my question is how can I setup URL for getbytsdate or getbyname or other some kind of custom get method? and how can I call?
I tried like this way=>
url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', TimeSheetAPIView.as_view()),
and I called like that
api/timesheets_ts/getbytsdate/?tsdate='test'
Its not work.
So please can u explain for the custom method in apiview and url setting?
In addition to your implementation, you just need to show your custom get request to your urls.py. Edit your urls.py as follows:
# urls.py
timesheet_getbytsdate_detail = TimeSheetAPIView.as_view({'get': 'getbytsdate'})
timesheet_detail = TimeSheetAPIView.as_view({'get': 'retrieve'})
urlpatterns = [
url(r'^timesheets_ts/getbytsdate/(?P<tsdate>[-\w]+)/$', getbytsdate_detail),
url(r'^timesheets_ts/(?P<pk>[0-9]+)/', timesheet_detail),
]
EDIT: You need to use the combination viewsets.GenericViewSet and mixins.RetrieveModelMixin instead of APIVewto get use of that:
class TimeSheetAPIView(viewsets.GenericViewSet, mixins.RetrieveModelMixin):
#action(methods=['get'], detail=False)
def getbytsdate(self, request):
return Response({"timesheet":"hello from getbydate"})
def retrieve(self, request, *args, **kwargs):
timesheet=self.get_object()
serializer = TimeSheetSerializer(timesheet)
return Response({serializer.data})
timesheet=TimeSheet.objects.all()
serializer = TimeSheetSerializer(timesheet,many=True)
return Response({"timesheet":serializer.data})

What is the meaning of detail argument in Django ViewSet?

I create a custom action method in Django ViewSet and I see detail argument. If I set detail=True I can't call this method from URL but if I set detail=False, I can call this method. May I know what is the meaning of detail argument?
Here is my viewset = >
class TimeSheetViewSet(viewsets.ModelViewSet):
queryset = TimeSheet.objects.all()
serializer_class = TimeSheetSerializer
#action(methods=['get'], detail=True)
def byhello(self, request):
return Response({"From Hello":"Got it"})
Here are router and URL patterns =>
router.register('timesheets_ts', TimeSheetViewSet, base_name='timesheets')
urlpatterns = [
path('api/', include(router.urls))
]
As the docs states, if you pass detail=True it means that that router will return you a single object whilst if you don't pass detail=True or pass detail=False it will return a list of objects.
One thing to have in mind is that if you are not doing anything or don’t need a single object in this function, you can set the detail=False
In your case it’d be something like:
#action(methods=['get'], detail=True)
def byhello(self, request, pk=None):
self.object = self.get_object()
return Response({"From Hello":"Got it"})

Add context to head of ListAPIView

I would like to add {'user': self.request.user} to the header of my ListAPIView.
For example, the JSON response would look like:
[
'user': testing_user,
{
id: 67,
slug: "slugy",
},
]
Is it possible to do this with this view?
class BookArchiveAPIView(generics.ListAPIView):
cache_timeout = 60 * 7
serializer_class = BookSerializer
queryset = Book.objects.all()
I know its too late but I needed same thing and just found on the documentation easily.
You don't need to pass the "request.user" to the view because DRF already gives it to you.
Here is the example:
class show_activities(generics.ListAPIView):
serializer_class = ActivitySerializer
def get_queryset(self):
username = self.request.user.username
return Activity.objects.filter(owner=username)
It's easy to find on documentation but I'm answering for the ones who couldn't see it.

Django rest framework, use different serializers in the same ModelViewSet

I would like to provide two different serializers and yet be able to benefit from all the facilities of ModelViewSet:
When viewing a list of objects, I would like each object to have an url which redirects to its details and every other relation appear using __unicode __ of the target model;
example:
{
"url": "http://127.0.0.1:8000/database/gruppi/2/",
"nome": "universitari",
"descrizione": "unitn!",
"creatore": "emilio",
"accesso": "CHI",
"membri": [
"emilio",
"michele",
"luisa",
"ivan",
"saverio"
]
}
When viewing the details of an object, I would like to use the default HyperlinkedModelSerializer
example:
{
"url": "http://127.0.0.1:8000/database/gruppi/2/",
"nome": "universitari",
"descrizione": "unitn!",
"creatore": "http://127.0.0.1:8000/database/utenti/3/",
"accesso": "CHI",
"membri": [
"http://127.0.0.1:8000/database/utenti/3/",
"http://127.0.0.1:8000/database/utenti/4/",
"http://127.0.0.1:8000/database/utenti/5/",
"http://127.0.0.1:8000/database/utenti/6/",
"http://127.0.0.1:8000/database/utenti/7/"
]
}
I managed to make all this work as I wish in the following way:
serializers.py
# serializer to use when showing a list
class ListaGruppi(serializers.HyperlinkedModelSerializer):
membri = serializers.RelatedField(many = True)
creatore = serializers.RelatedField(many = False)
class Meta:
model = models.Gruppi
# serializer to use when showing the details
class DettaglioGruppi(serializers.HyperlinkedModelSerializer):
class Meta:
model = models.Gruppi
views.py
class DualSerializerViewSet(viewsets.ModelViewSet):
"""
ViewSet providing different serializers for list and detail views.
Use list_serializer and detail_serializer to provide them
"""
def list(self, *args, **kwargs):
self.serializer_class = self.list_serializer
return viewsets.ModelViewSet.list(self, *args, **kwargs)
def retrieve(self, *args, **kwargs):
self.serializer_class = self.detail_serializer
return viewsets.ModelViewSet.retrieve(self, *args, **kwargs)
class GruppiViewSet(DualSerializerViewSet):
model = models.Gruppi
list_serializer = serializers.ListaGruppi
detail_serializer = serializers.DettaglioGruppi
# etc.
Basically I detect when the user is requesting a list view or a detailed view and change serializer_class to suit my needs. I am not really satisfied with this code though, it looks like a dirty hack and, most importantly, what if two users request a list and a detail at the same moment?
Is there a better way to achieve this using ModelViewSets or do I have to fall back using GenericAPIView?
EDIT:
Here's how to do it using a custom base ModelViewSet:
class MultiSerializerViewSet(viewsets.ModelViewSet):
serializers = {
'default': None,
}
def get_serializer_class(self):
return self.serializers.get(self.action,
self.serializers['default'])
class GruppiViewSet(MultiSerializerViewSet):
model = models.Gruppi
serializers = {
'list': serializers.ListaGruppi,
'detail': serializers.DettaglioGruppi,
# etc.
}
Override your get_serializer_class method. This method is used in your model mixins to retrieve the proper Serializer class.
Note that there is also a get_serializer method which returns an instance of the correct Serializer
class DualSerializerViewSet(viewsets.ModelViewSet):
def get_serializer_class(self):
if self.action == 'list':
return serializers.ListaGruppi
if self.action == 'retrieve':
return serializers.DettaglioGruppi
return serializers.Default # I dont' know what you want for create/destroy/update.
You may find this mixin useful, it overrides the get_serializer_class method and allows you to declare a dict that maps action and serializer class or fallback to the usual behavior.
class MultiSerializerViewSetMixin(object):
def get_serializer_class(self):
"""
Look for serializer class in self.serializer_action_classes, which
should be a dict mapping action name (key) to serializer class (value),
i.e.:
class MyViewSet(MultiSerializerViewSetMixin, ViewSet):
serializer_class = MyDefaultSerializer
serializer_action_classes = {
'list': MyListSerializer,
'my_action': MyActionSerializer,
}
#action
def my_action:
...
If there's no entry for that action then just fallback to the regular
get_serializer_class lookup: self.serializer_class, DefaultSerializer.
"""
try:
return self.serializer_action_classes[self.action]
except (KeyError, AttributeError):
return super(MultiSerializerViewSetMixin, self).get_serializer_class()
This answer is the same as the accepted answer but I prefer to do in this way.
Generic views
get_serializer_class(self):
Returns the class that should be used for the serializer. Defaults to returning the serializer_class attribute.
May be overridden to provide dynamic behavior, such as using different serializers for reading and write operations or providing different serializers to the different types of users.
the serializer_class attribute.
class DualSerializerViewSet(viewsets.ModelViewSet):
# mapping serializer into the action
serializer_classes = {
'list': serializers.ListaGruppi,
'retrieve': serializers.DettaglioGruppi,
# ... other actions
}
default_serializer_class = DefaultSerializer # Your default serializer
def get_serializer_class(self):
return self.serializer_classes.get(self.action, self.default_serializer_class)
Regarding providing different serializers, why is nobody going for the approach that checks the HTTP method? It's clearer IMO and requires no extra checks.
def get_serializer_class(self):
if self.request.method == 'POST':
return NewRackItemSerializer
return RackItemSerializer
Credits/source: https://github.com/encode/django-rest-framework/issues/1563#issuecomment-42357718
Based on #gonz and #user2734679 answers I've created this small python package that gives this functionality in form a child class of ModelViewset. Here is how it works.
from drf_custom_viewsets.viewsets.CustomSerializerViewSet
from myapp.serializers import DefaltSerializer, CustomSerializer1, CustomSerializer2
class MyViewSet(CustomSerializerViewSet):
serializer_class = DefaultSerializer
custom_serializer_classes = {
'create': CustomSerializer1,
'update': CustomSerializer2,
}
Just want to addon to existing solutions. If you want a different serializer for your viewset's extra actions (i.e. using #action decorator), you can add kwargs in the decorator like so:
#action(methods=['POST'], serializer_class=YourSpecialSerializer)
def your_extra_action(self, request):
serializer = self.get_serializer(data=request.data)
...
Although pre-defining multiple Serializers in or way or another does seem to be the most obviously documented way, FWIW there is an alternative approach that draws on other documented code and which enables passing arguments to the serializer as it is instantiated. I think it would probably tend to be more worthwhile if you needed to generate logic based on various factors, such as user admin levels, the action being called, perhaps even attributes of the instance.
The first piece of the puzzle is the documentation on dynamically modifying a serializer at the point of instantiation. That documentation doesn't explain how to call this code from a viewset or how to modify the readonly status of fields after they've been initated - but that's not very hard.
The second piece - the get_serializer method is also documented - (just a bit further down the page from get_serializer_class under 'other methods') so it should be safe to rely on (and the source is very simple, which hopefully means less chance of unintended side effects resulting from modification). Check the source under the GenericAPIView (the ModelViewSet - and all the other built in viewset classes it seems - inherit from the GenericAPIView which, defines get_serializer.
Putting the two together you could do something like this:
In a serializers file (for me base_serializers.py):
class DynamicFieldsModelSerializer(serializers.ModelSerializer):
"""
A ModelSerializer that takes an additional `fields` argument that
controls which fields should be displayed.
"""
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Adding this next line to the documented example
read_only_fields = kwargs.pop('read_only_fields', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
# another bit we're adding to documented example, to take care of readonly fields
if read_only_fields is not None:
for f in read_only_fields:
try:
self.fields[f].read_only = True
exceptKeyError:
#not in fields anyway
pass
Then in your viewset you might do something like this:
class MyViewSet(viewsets.ModelViewSet):
# ...permissions and all that stuff
def get_serializer(self, *args, **kwargs):
# the next line is taken from the source
kwargs['context'] = self.get_serializer_context()
# ... then whatever logic you want for this class e.g:
if self.action == "list":
rofs = ('field_a', 'field_b')
fs = ('field_a', 'field_c')
if self.action == “retrieve”:
rofs = ('field_a', 'field_c’, ‘field_d’)
fs = ('field_a', 'field_b’)
# add all your further elses, elifs, drawing on info re the actions,
# the user, the instance, anything passed to the method to define your read only fields and fields ...
# and finally instantiate the specific class you want (or you could just
# use get_serializer_class if you've defined it).
# Either way the class you're instantiating should inherit from your DynamicFieldsModelSerializer
kwargs['read_only_fields'] = rofs
kwargs['fields'] = fs
return MyDynamicSerializer(*args, **kwargs)
And that should be it! Using MyViewSet should now instantiate your MyDynamicSerializer with the arguments you'd like - and assuming your serializer inherits from your DynamicFieldsModelSerializer, it should know just what to do.
Perhaps its worth mentioning that it can makes special sense if you want to adapt the serializer in some other ways …e.g. to do things like take in a read_only_exceptions list and use it to whitelist rather than blacklist fields (which I tend to do). I also find it useful to set the fields to an empty tuple if its not passed and then just remove the check for None ... and I set my fields definitions on my inheriting Serializers to 'all'. This means no fields that aren't passed when instantiating the serializer survive by accident and I also don't have to compare the serializer invocation with the inheriting serializer class definition to know what's been included...e.g within the init of the DynamicFieldsModelSerializer:
# ....
fields = kwargs.pop('fields', ())
# ...
allowed = set(fields)
existing = set(self.fields)
for field_name in existing - allowed:
self.fields.pop(field_name)
# ....
NB If I just wanted two or three classes that mapped to distinct actions and/or I didn't want any specially dynamic serializer behaviour, I might well use one of the approaches mentioned by others here, but I thought this worth presenting as an alternative, particularly given its other uses.
With all other solutions mentioned, I was unable to find how to instantiate the class using get_serializer_class function and unable to find custom validation function as well. For those who are still lost just like I was and want full implementation please check the answer below.
views.py
from rest_framework.response import Response
from project.models import Project
from project.serializers import ProjectCreateSerializer, ProjectIDGeneratorSerializer
class ProjectViewSet(viewsets.ModelViewSet):
action_serializers = {
'generate_id': ProjectIDGeneratorSerializer,
'create': ProjectCreateSerializer,
}
permission_classes = [IsAuthenticated]
def get_serializer_class(self):
if hasattr(self, 'action_serializers'):
return self.action_serializers.get(self.action, self.serializer_class)
return super(ProjectViewSet, self).get_serializer_class()
# You can create custom function
def generate_id(self, request):
serializer = self.get_serializer_class()(data=request.GET)
serializer.context['user'] = request.user
serializer.is_valid(raise_exception=True)
return Response(serializer.validated_data, status=status.HTTP_200_OK)
def create(self, request, **kwargs):
serializer = self.get_serializer_class()(data=request.data)
serializer.context['user'] = request.user
serializer.is_valid(raise_exception=True)
return Response(serializer.validated_data, status=status.HTTP_200_OK)
serializers.py
import random
from rest_framework import serializers
from project.models import Project
class ProjectIDGeneratorSerializer(serializers.Serializer):
def update(self, instance, validated_data):
pass
def create(self, validated_data):
pass
projectName = serializers.CharField(write_only=True)
class Meta:
fields = ['projectName']
def validate(self, attrs):
project_name = attrs.get('projectName')
project_id = project_name.replace(' ', '-')
return {'projectID': project_id}
class ProjectCreateSerializer(serializers.Serializer):
def update(self, instance, validated_data):
pass
def create(self, validated_data):
pass
projectName = serializers.CharField(write_only=True)
projectID = serializers.CharField(write_only=True)
class Meta:
model = Project
fields = ['projectName', 'projectID']
def to_representation(self, instance: Project):
data = dict()
data['projectName'] = instance.name
data['projectID'] = instance.projectID
data['createdAt'] = instance.createdAt
data['updatedAt'] = instance.updatedAt
representation = {
'message': f'Project {instance.name} has been created.',
}
return representation
def validate(self, attrs):
print('attrs', dict(attrs))
project_name = attrs.get('projectName')
project_id = attrs.get('projectID')
if Project.objects.filter(projectID=project_id).first():
raise serializers.ValidationError(f'Project with ID {project_id} already exist')
project = Project.objects.create(projectID=project_id,
name=project_name)
print('user', self.context['user'])
project.user.add(self.context["user"])
project.save()
return self.to_representation(project)
urls.py
from django.urls import path
from .views import ProjectViewSet
urlpatterns = [
path('project/generateID', ProjectViewSet.as_view({'get': 'generate_id'})),
path('project/create', ProjectViewSet.as_view({'post': 'create'})),
]
models.py
# Create your models here.
from django.db import models
from authentication.models import User
class Project(models.Model):
id = models.AutoField(primary_key=True)
projectID = models.CharField(max_length=255, blank=False, db_index=True, null=False)
user = models.ManyToManyField(User)
name = models.CharField(max_length=255, blank=False)
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
You can map your all serializers with the action using a dictionary in class and then get them from "get_serializer_class" method. Here is what I am using to get different serializers in different cases.
class RushesViewSet(viewsets.ModelViewSet):
serializer_class = DetailedRushesSerializer
queryset = Rushes.objects.all().order_by('ingested_on')
permission_classes = (IsAuthenticated,)
filter_backends = (filters.SearchFilter,
django_filters.rest_framework.DjangoFilterBackend, filters.OrderingFilter)
pagination_class = ShortResultsSetPagination
search_fields = ('title', 'asset_version__title',
'asset_version__video__title')
filter_class = RushesFilter
action_serializer_classes = {
"create": RushesSerializer,
"update": RushesSerializer,
"retrieve": DetailedRushesSerializer,
"list": DetailedRushesSerializer,
"partial_update": RushesSerializer,
}
def get_serializer_context(self):
return {'request': self.request}
def get_serializer_class(self):
try:
return self.action_serializer_classes[self.action]
except (KeyError, AttributeError):
error_logger.error("---Exception occurred---")
return super(RushesViewSet, self).get_serializer_class()