Is it a good practice to override list() in Django Rest Framework? - django-rest-framework

My question is all in the title.
I am using DRF mixins and I would like to know if I can override method list() in class ListModelMixin. I need to add some computed information to my data.
The code source is as below and you can find it here
class ListModelMixin(object):
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)

Yes, it is a common practice, if you need any different behavior.
This practice is also mentioned in the DRF documentation. So, you can safely do it.
(See: examples )

Related

Accessing ViewSet object list to provide extra context to serializer

I am attempting to add context to a serializer within a ModelViewSet which is dependent on the current paged object list in context. I'll explain with an example.
I am building a viewsets.ModelViewSet that lists Users and a list of favorite_foods. However- the list of user's favorite foods in some external microservice accessible via API. Building a ViewSet to collect objects and performing HTTP requests on each is trivial, we can do something like this:
class UserViewSet(viewsets.ViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserSerializer(serializers.ModelSerializer):
favorite_foods = serializers.SerializerMethodField()
def get_favorite_foods(self, instance):
# performs an HTTP call and returns a list[] of foods.
return evil_coupled_microservice_client.get_user_food_list(instance)
class Meta:
model = User
fields = ('id', 'name', 'favorite_foods')
The issue is (aside from some ugly infrastructure coupling) this is going to make an HTTP request count equivalent to the page size. Instead- it would be great if I could prefetch the favorite food lists for all users on the page in a single HTTP call, and just add them into context, like this:
class UserViewSet(viewsets.ViewSet):
def get_serializer_context(self):
context = super().get_serializer_context()
users = <-- This is where I want to know what users are in the current filtered, paginated response.
users_food_dict = evil_coupled_microservice_client.get_many_users_food_list(users)
context.update({'usesr_foods': users_food_dict})
return context
However- it doesn't appear there is any way to fetch the object list that's going to be serialized. Although (I'm fairly sure) get_serializer_context is called after the queryset is filtered and paginated, I'm not sure how to access it without doing some really hacking re-compiling of the queryset based on the query_params and other pieces attached to the class.
I'll post my current solution. It's not terrible, but I'm still hoping for a cleaner built-in.
class UserViewSet(viewsets.ViewSet):
...
def list(self, request, *args, **kwargs):
# Overrwite `ListModelMixin` and store current set
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
self.current_queryset = page
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
self.current_queryset = queryset
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
This is untested so far (not sure about functionality on Detail endpoints for instance) allows for the current_queryset to be fetched within the serializer context.

Using django-filter overriding list method in drf

I'm using django-filter to filter my viewsets in drf.
When I have a ModelViewset, works fine like example bellow:
class MyExampleViewSet(viewsets.ModelViewSet):
queryset = myqueryset
model = ModelExample
filter_backends = (DjangoFilterBackend, OrderingFilter,)
filterset_fields = {
"field_example": ["exact", "icontains"],
"another_field_example": ["exact", "range"],
}
serializer_class = MyExampleViewSet
My problem is when I override the list method using a ViewSet, like this:
class MyExampleViewSet(viewsets.ViewSet):
def list(self, request, queryset=queryset, *args, **kwargs):
return something
In this case my filters does not working. Is there a way of using django-filter in this case (overriding list)?
I know what I can do with query_params, but I would like to use django-filter.
First, you should take a look at how the list method is implemented:
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
return self.get_paginated_response(serializer.data)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
Django-filter is applied at this point queryset = self.filter_queryset(self.get_queryset()).
So if you want to override the list method but keep the the filtering feature, then make sure to call self.filter_queryset() with the queryset.

DRF Serializer custom create

I don't know if I'm doing this the right way, but I'm having problems with saving some relations with DRF serializers.
Let's say I have a MessageBoard and some MessageBoardPosts
Post has a serializer like:
class MessageBoardPostSerializer(serializers.ModelSerializer):
class Meta:
model = MessageBoardPost
fields = '__all__'
I want to add a Post by posting to /api/messageBoards/[PK]/create_post/
To do this, I added an action to the MessageBoard Viewset:
#action(detail=True, methods=['post'], permission_classes=[MatchesMessageboardVisibility])
def create_post(self, request, pk=None):
# Messageboard to post to
messageBoard = MessageBoard.objects.get(pk=pk)
if messageBoard is not None:
serializer = MessageBoardPostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
Since MessageBoard is a required FK on a post, I get validation errors when creating the post in the viewset.
What's the best way to solve this?
Serializer (i assume that "message_board" is ForeignKey in MessageBoardPost model):
class MessageBoardPostSerializer(serializers.ModelSerializer):
# this is read only by default which means serializer will not require that field
message_board = serializers.StringRelatedField()
class Meta:
model = MessageBoardPost
fields = '__all__'
Viewset action:
#action(detail=True, methods=['post'], permission_classes=[MatchesMessageboardVisibility])
def create_post(self, request, pk=None):
# Messageboard to post to
messageBoard = get_object_or_404(MessageBoard, pk=pk)
serializer = MessageBoardPostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
# here you can pass data without validation directly to the save method
serializer.save(message_board=messageBoard)
return Response(serializer.data)
you should write your variables in snake_case style like "message_board" etc.
for more advanced crud you should make url like /api/message-boards/PK/posts/ where you will POST your posts and message_board should be prefetched in overrited initial method
You can pass the MessageBoard as context to the serializer:
views.py
from django.shortcuts import get_object_or_404
#action(detail=True, methods=['post'], permission_classes=[MatchesMessageboardVisibility])
def create_post(self, request, pk=None):
# Messageboard to post to
message_board = get_object_or_404(MessageBoard, pk=pk)
context = {'message_board': message_board}
serializer = MessageBoardPostSerializer(data=request.data, context=context)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(serializer.data)
serializers.py
class MessageBoardPostSerializer(serializers.ModelSerializer):
class Meta:
model = MessageBoardPost
fields = '__all__'
def create(self, validated_data):
post = MessageBoardPost(**validated_data)
post.message_board = self.context['message_board']
post.save()
return post

DRF name undefined in custom serializer

When I try to hit my api/atoms/ endpoint in the browser, I am getting a name undefined error in the views.py file, but it has a base name in urls.
Note: this is a non-model serializer and a ViewSet.
error
...views.py", line 74, in list
instance = atom.values(), many=True)
NameError: name 'atoms' is not defined
views.py
class AtomViewSet(viewsets.ViewSet):
serializer_class = AtomSerializer
def list(self, request):
serializer = AtomSerializer(
instance = atoms.values(), many=True) #<-------------
return Response(serializer.data)
urls.py
# for viewsets in views.py
router = DefaultRouter()
router.register(r'snippets', views.SnippetViewSet)
router.register(r'atoms', views.AtomViewSet, base_name='atoms')
urlpatterns = [
path('', views.api_root),
path('', include(router.urls)),
]
serializer.py
class AtomSerializer(serializers.Serializer):
uid = UniqueIdProperty()
created_at = DateTimeProperty()
updated_at = DateTimeProperty()
charge = IntegerProperty()
mass = FloatProperty()
def create(self, validated_data):
return Atom(id=None, **validated_data)
def update(self, instance, validated_data):
for field, value in validated_data.items():
setattr(instance, field, value)
return instance
This is a basic python NameError exception raised when a local or global name is not found.
The variable atoms is not defined in the list() method or globally, that's why the python interpreter raised the exception.
In your code, you'd write atoms.values(), which forces me to think that you are dealing with a QuerySet, which might be an Atom model.
class AtomViewSet(viewsets.ViewSet):
serializer_class = AtomSerializer
def list(self, request):
serializer = AtomSerializer(instance=Atom.objects.all(), many=True)
return Response(serializer.data)
Note: this is a non-model serializer and a ViewSet.
You are doing create and update operations in your AtomSerializer class, and those are directly connected to the model. I don't see any particular reason that pulls you back from using a ModelSerializer here. Apart from that, you are using the routers, which become a good choice when you deal with the CRUD operations, hence I strongly suggest you use the combination of ModelViewset and ModelSerializer in your code.
In your views.py you did not define atom, you need to define it first before using it or else you will get that error.
class AtomViewSet(viewsets.ViewSet):
serializer_class = AtomSerializer
def list(self, request):
# You need to define the atom first before passing it to your AtomSerializer
atoms = [] # or atom = Atom.objects.all()
serializer = AtomSerializer(
data=atoms,
many=True
)
return Response(serializer.data)

Django Rest Framework - separate serializer class per method in model based API view

Say I have a simple Django REST Framework view that's extending multiple model classes and serves all the methods in one URL endpoint:
class UserAPIView(RetrieveAPIView, DestroyAPIView, BaseObjectAPIView):
permission_classes = (IsAuthenticated, )
serializer_class = UserSerializer
def get_serializer_class(self, *args, **kwargs):
# return different serializer depending on method??
# return UserUpdateSerializer
return UserViewSerializer
def get(self, request, *args, **kwargs):
"""
Retrieve user details
"""
# ...
return Response(data={'result': "OK"}, status=200)
def delete(self, request, pk):
"""
Delete user
"""
# ...
return Response(data={'result': "OK"}, status=200)
def put(self, request, pk):
"""
Change user
"""
# ...
return Response(data={'result': "OK"}, status=200)
Now I need to use different serializers per method, as my get-method will use different fields than my put-method, example serializers:
class UserViewSerializer(serializers.ModelSerializer):
firstname = serializers.Field(source='firstname')
lastname = serializers.Field(source='lastname')
username = serializers.Field(source='username')
class Meta:
model = User
class UserUpdateSerializer(serializers.ModelSerializer):
firstname = serializers.Field(source='firstname')
lastname = serializers.Field(source='lastname')
class Meta:
model = User
Is it possible to use different serializers for each method in my model based API view?
UPDATE:
I know how to use different serializers inside the methods themselves.
But I need to get the Browsable API generated by Swagger (Django module rest_framework_swagger) to retrieve different serializers for each method.
I can see that loading the API browser page triggers get_serializer_class, but inside that method, I don't know what method Swagger tries to get the serializer for.
How can I get rest_framework_swagger to retrieve different serializers per method?
I think there are at least two ways to achieve this:
You simply set the serializer that you want in each of your methods. Like this:
def get(self, request, *args, **kwargs):
self.serializer_class = UserViewSerializer
# ...
return Response(data={'result': "OK"}, status=200)
You override the get_Serializer_class method. Like this:
def get_serializer_class(self, *args, **kwargs):
if self.request.method == 'POST':
return UserUpdateSerializer
return UserViewSerializer
Hope this helps.
I suppose you could use yaml docstring on each method to override serializers. Like:
def put(self, request, pk):
"""Change user
---
serializer: .serializers.UserUpdateSerializer
"""
# ...
return Response(data={'result': "OK"}, status=200)

Resources