You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesi贸n a prueba de IA

Antes: $249

Currency
$209
Suscr铆bete

Termina en:

0 D铆as
2 Hrs
13 Min
35 Seg

Manejos de Acciones con ViewSet en Django REST Framework

14/21
Resources

When creating APIs in Django REST Framework, we not only work with URLs for resources, but also with actions that allow us to execute specific operations, such as paying a card or, in this case, managing a doctor's vacation.

How to add a field to control the vacation status in a model?

  • In the Doctor model, we add the is_on_vacation field, which will be a boolean field with default value False.
  • We create the migrations with manage.py makemigrations and then run migrate to apply the changes to the database.

How to create a custom action to enable or disable vacations?

  • In Django REST Framework ViewSets, custom actions are created with the @action decorator. We import the decorator from rest_framework.decorators.
  • We define a method called toggle_vacation with the decorator and specify that only the POST method will be allowed.
  • The decorator also needs the parameter detail=True for the action to be applied to a specific resource, such as a doctor identified by its ID in the URL.

How to implement the logic to toggle the vacation state?

  • We use the get_object() method of the ViewSet to get the current Doctor object.
  • The logic toggles between True and False for the is_on_vacation field. If it is set to True, it changes it to False and vice versa.
  • The Doctor object is saved and a response is returned using Response to report the updated status.

How to improve the idempotency and clarity of the endpoint?

  • Instead of toggling between True and False, we create two separate actions: one to enable vacation(set_on_vacation) and one to disable it(set_off_vacation).
  • This ensures that each POST request has a predictable behavior, which improves the endpoint's idempotency.

How to adjust the action URL to improve readability?

  • URLs generated from the method name can have underscores, which is not ideal for SEO and readability. We use the url_path parameter inside the @action decorator to define URLs with hyphens, e.g. set-on-vacation.

How to test custom actions?

  • From the Django REST Framework interface, we test the actions by sending POST requests to the generated URLs.
  • We verify that the doctors can be marked as on vacation or not, and that the is_on_vacation field changes correctly in the database.

How to replicate this process for other resources?

  • Following this pattern, we can create actions for other resources. For example, a patient may need to get a medical report in JSON format, which would be a custom action in the Patient ViewSet.

Contributions 4

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Dejo el reto por aqu铆: ```python from rest_framework import viewsets from rest_framework.decorators import action from rest_framework.response import Response from .models import Patient, MedicalHistory from .serializers import MedicalHistorySerializer class PatientViewSet(viewsets.ModelViewSet): queryset = Patient.objects.all() serializer_class = MedicalHistorySerializer # Se utiliza en las acciones personalizadas # Acci贸n personalizada para agregar un nuevo historial cl铆nico @action(['POST'], detail=True, url_path='add-medical-history') def add_medical_history(self, request, pk=None): patient = self.get_object() # Obtener el paciente por su pk data = request.data # Obtener los datos del historial cl铆nico desde la solicitud data['patient'] = patient.id # Asignar el paciente al historial cl铆nico serializer = MedicalHistorySerializer(data=data) if serializer.is_valid(): serializer.save() # Guardar el historial cl铆nico return Response({"status": "Medical history added"}, status=201) return Response(serializer.errors, status=400) # Retornar errores si los datos no son v谩lidos # Acci贸n personalizada para listar el historial cl铆nico de un paciente @action(['GET'], detail=True, url_path='medical-history') def list_medical_history(self, request, pk=None): patient = self.get_object() # Obtener el paciente por su pk medical_history = MedicalHistory.objects.filter(patient=patient) # Filtrar el historial cl铆nico por paciente serializer = MedicalHistorySerializer(medical_history, many=True) return Response(serializer.data) # Retornar el historial cl铆nico en formato JSON ```
My solutiosn 馃: ```js class ListPatientView(viewsets.ModelViewSet): serializer_class = PatientSerializer queryset = Patient.objects.all() @action(["GET"], detail=True, url_path="get-medical-history") def get_medical_history(self, request, pk): patient = self.get_object() return Response({"medical_history": patient.medical_history}) ```
Ventajas de utilizar acciones personalizadas en viewsets con Django Rest Framework: 1. **Flexibilidad**: Permiten agregar funcionalidades espec铆ficas que no est谩n cubiertas por las acciones predeterminadas. 2. **Reutilizaci贸n de l贸gica**: Facilitan la reutilizaci贸n de l贸gica com煤n en diferentes partes de la API. 3. **URLs claras y espec铆ficas**: Generan rutas URL intuitivas y espec铆ficas para las acciones personalizadas. 4. **Mejor organizaci贸n**: Mantienen la l贸gica relacionada en un solo lugar, mejorando la estructura del c贸digo. 5. **Facilitan la extensi贸n**: Hacen m谩s sencillo extender la API con nuevas funcionalidades sin modificar las acciones b谩sicas.
Nueva clase, nuevos conocimientos, super genial todo :')