converting Django generic class based LISTVIEW to Rest framework LISTAPIVIEW

452 views Asked by At

I need help to convert the below class-based LISTVIEW to the rest framework LISTAPIVIEW because I want to authenticate users using permission classes simple JWT authentication. thanks

class MessagesModelList(ListView):
http_method_names = ['get', ]
paginate_by = getattr(settings, 'MESSAGES_PAGINATION', 500)

def get_queryset(self):
    if self.kwargs.get('dialog_with'):
        qs = MessageModel.objects \
            .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) |
                    Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \
            .select_related('sender', 'recipient')
    else:
        qs = MessageModel.objects.filter(Q(recipient=self.request.user) |
                                         Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file')

    return qs.order_by('-created')

def render_to_response(self, context, **response_kwargs):
    user_pk = self.request.user.pk
    data = [serialize_message_model(i, user_pk)
            for i in context['object_list']]
    page: Page = context.pop('page_obj')
    paginator: Paginator = context.pop('paginator')
    return_data = {
        'page': page.number,
        'pages': paginator.num_pages,
        'data': data
    }
    return JsonResponse(return_data, **response_kwargs)
1

There are 1 answers

0
LiquidDeath On

you need to create the below files and and try the following

serializer.py

from rest_framework import serializers
from rest_framework.pagination import PageNumberPagination
from .models import MessageModel

class CustomPagination(PageNumberPagination):
    page_size = 500
    page_size_query_param = 'page_size'
    max_page_size = 10000

class MessagesModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = MessageModel
        fields = "__all__" #use this if you want all the fields of your model available
        fields = ['field1','field2', etc..] #use this if you want specific fields of your model

views.py

from .models import MessageModel
from rest_framework import mixins,viewsets
from .serializer import MessagesModelSerializer,CustomPagination

class MessagesModelListView(mixins.ListModelMixin,
                             viewsets.GenericViewSet):
    serializer_class = MessagesModelSerializer
    pagination_class = CustomPagination

    def get_queryset(self):
        if self.kwargs.get('dialog_with'):
            qs = MessageModel.objects \
                .filter(Q(recipient=self.request.user, sender=self.kwargs['dialog_with']) |
                        Q(sender=self.request.user, recipient=self.kwargs['dialog_with'])) \
                .select_related('sender', 'recipient')
        else:
            qs = MessageModel.objects.filter(Q(recipient=self.request.user) |
                                            Q(sender=self.request.user)).prefetch_related('sender', 'recipient', 'file')

        return qs.order_by('-created')

urls.py

from .views import MessageModelListView
from rest_framework.routers import DefaultRouter

router=DefaultRouter()
router.register('messages', MessagesModelList, 'messages')

This is a basic example of how you can create ListView using DRF. if you need more customization, please refer the documentation : https://www.django-rest-framework.org/api-guide/generic-views/