Cecilia

Crear APi de persona

from rest_framework import routers
from persona.api import PersonaViewSet
router = routers.DefaultRouter()
router.register('persona', PersonaViewSet)
... ...
... ... @@ -39,6 +39,8 @@ INSTALLED_APPS = [
'django.contrib.staticfiles',
# Aplicaciones de tercero
'django_extensions',
'rest_framework',
'django_filters',
# Aplicaciones propias
'persona',
... ... @@ -77,6 +79,18 @@ TEMPLATES = [
WSGI_APPLICATION = 'capacitacion.wsgi.application'
# CONFIGURACION DE REST FRAMEWORK
REST_FRAMEWORK = {
# Use Django's standard `django.contrib.auth` permissions,
# or allow read-only access for unauthenticated users.
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
],
'DEFAULT_RENDERER_CLASSES': [
'rest_framework.renderers.JSONRenderer',
'rest_framework.renderers.BrowsableAPIRenderer',
]
}
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
... ...
... ... @@ -15,9 +15,14 @@ Including another URLconf
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from capacitacion.routers import router
urlpatterns = [
path('', RedirectView.as_view(url='/admin/')),
path('admin/', admin.site.urls),
path('persona/', include('persona.urls'), name='persona'),
path('api/v1/', include((router.urls, 'capacitacion'), namespace='capacitacion')),
# path('persona/', include('organismo.urls'), name='persona')
]
... ...
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticated
from persona.filters import PersonaFilter
from persona.models import Persona
from persona.serializers import PersonaSerializer
class PersonaViewSet(viewsets.ModelViewSet):
queryset = Persona.objects.all()
serializer_class = PersonaSerializer
filterset_class = PersonaFilter
filter_backends = [DjangoFilterBackend]
permission_classes = (IsAuthenticated,)
... ...
from django_filters import rest_framework as filters
from persona.models import Persona
class PersonaFilter(filters.FilterSet):
class Meta:
model = Persona
fields = ('nombre', 'fecha_nacimiento')
nombre = filters.CharFilter(field_name='nombre', lookup_expr='icontains')
... ...
import datetime
from rest_framework import serializers
from persona.models import Persona
class PersonaSerializer(serializers.ModelSerializer):
class Meta:
model = Persona
fields = ('nombre', 'apellido', 'documento_identidad', 'fecha_nacimiento', 'organismo', 'edad')
edad = serializers.SerializerMethodField(method_name='calcular_edad')
def calcular_edad(self, persona):
today = datetime.date.today()
diferencia = today - persona.fecha_nacimiento
edad = diferencia.days
edad = edad / 365
return int(edad)
... ...
django==3.2.7
pytest==6.2.2
pytest-django==4.1.0
pytest-mock==3.5.1
djangorestframework==3.12.4
django-filter==21.1
... ...