analitics

Pages

Saturday, April 27, 2019

Django REST framework - part 001.

Today I will introduce you a tutorial to fix some of the necessary elements presented in the old tutorial.
The manage tool shell can also give us some info:
C:\Python373\Scripts\example>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from test001.models import test
>>> from django.db.models import Count, Min, Max, Avg
>>> out = test.objects.all
>>> out
...
One note about error method, do not use like this:
>>> out = test.objects.all
>>> out[0]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'method' object is not subscriptable
The correct way method is:
>>> out = test.objects.all()
>>> out
]>
>>> out[0]

>>> vars(out[0])
{'_state': , 'id'
: 1, 'first_name': 'Cătălin George', 'last_name': 'Feștilă'}
We can use the annotate.
This issue can solve it into this way:
>>> minimal = test.objects.annotate(Min('last_name'))
>>> minimal
]>
>>> minimal[0]

>>> vars(minimal[0])
{'_state': , 'id'
: 1, 'first_name': 'Cătălin George', 'last_name': 'Feștilă', 'last_name__min': '
Feștilă'}
See the result of the annotate add the last_name__min value.
I created another class named city with just one field named city_name and I fill with one value:
All changes are posted at the end of this tutorial.
Let's test with the shell some of these new changes:
C:\Python373\Scripts\example>python manage.py shell
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit 
(AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from test001.models import test,city
>>> from django.db.models import Count, Min, Max, Avg
>>> out_test = test.objects.all()
>>> out_city = city.objects.all()
>>> out_test
]>
>>> out_city
]>
>>> vars(out_city[0])
{'_state': , 'id'
: 1, 'city_name': 'Fălticeni'}
We can easy test the new example:
>>> minimal = test.objects.annotate(Min('last_name'))
>>> minimal
]>
>>> vars(minimal[0])
{'_state': , 'id'
: 1, 'first_name': 'Cătălin George', 'last_name': 'Feștilă', 'last_name__min': '
Feștilă'}
>>> minimal = city.objects.annotate(Min('city_name'))
>>> minimal
]>
>>> vars(minimal[0])
{'_state': , 'id'
: 1, 'city_name': 'Fălticeni', 'city_name__min': 'Fălticeni'}
>>> filter_test = test.objects.filter(id = 1)
>>> vars(filter_test)
{'model': , '_db': None, '_hints': {}, 'query': 
, '_result_cache': 
None, '_sticky_filter': False, '_for_write': False, '_prefetch_related_lookups':
(), '_prefetch_done': False, '_known_related_objects': {}, '_iterable_class': , '_fields': None}
>>> vars(filter_test[0])
{'_state': , 'id'
: 1, 'first_name': 'Cătălin George', 'last_name': 'Feștilă'}
Feel free to test with my old and the new example:
# models.py
from django.db import models

class test(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    
class city(models.Model):
    city_name = models.CharField(max_length=30)
#admin.py
from django.contrib import admin
from .models import test, city
admin.site.register(test)
admin.site.register(city)
#serializers.py
from rest_framework import serializers
from .models import test, city

class test_serializer(serializers.ModelSerializer):
    class Meta:
        model = test
        fields = ('id', 'first_name', 'last_name')

class city_serializer(serializers.ModelSerializer):        
    class Meta:
        model = city
        fields = ('id', 'city_name')
#views.py
from django.shortcuts import render
from rest_framework import viewsets
from .models import test, city
from .serializers import test_serializer, city_serializer

class test_view(viewsets.ModelViewSet):
    #query to get all information from database
    queryset = test.objects.all()
    serializer_class = test_serializer

class city_view(viewsets.ModelViewSet):
    #query to get all information from database
    queryset = city.objects.all()
    serializer_class = city_serializer
#urls.py
from django.urls import path, include
from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('test001', views.test_view)
router.register('city', views.city_view)
#add to path 
urlpatterns = [
    path('', include(router.urls))
]