Answers for "django rest framework viewset"

1

django rest framework viewset

from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from myapps.serializers import UserSerializer
from rest_framework import viewsets
from rest_framework.response import Response

class UserViewSet(viewsets.ViewSet):
    """
    A simple ViewSet for listing or retrieving users.
    """
    def list(self, request):
        queryset = User.objects.all()
        serializer = UserSerializer(queryset, many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk=None):
        queryset = User.objects.all()
        user = get_object_or_404(queryset, pk=pk)
        serializer = UserSerializer(user)
        return Response(serializer.data)
Posted by: Guest on August-19-2021
2

django rest framework viewset perform_update

def perform_update(self, serializer):
    # Save with the new value for the target model fields
    user = self.request.user
    userid = str(user.id)
    serializer.save(stu_enrolled_classes=userid)
# The above def is in viewset and you can specify what field else can be edited in the API "PUT",
# Here We just set the stu_enrolled_classes field with is relation to the user to be the current user that send the "PUT" request.
Posted by: Guest on September-13-2020
0

drf viewsets

class AccountViewSet(viewsets.ReadOnlyModelViewSet):
    """
    A simple ViewSet for viewing accounts.
    """
    queryset = Account.objects.all()
    serializer_class = AccountSerializer
Posted by: Guest on December-29-2020

Code answers related to "django rest framework viewset"

Python Answers by Framework

Browse Popular Code Answers by Language