Starting with DJango
Here I am starting the DJango project keeping some flow in mind.
- Setup
- Database model that django ORM will manage
- Serialize model
- Setup Django rest framework
- Create rest endpoints
Please collect the full code from here:
Steps
- Installed python
- Installed django : py -m pip install Django
- Added the django-install into the path
Folder Structure default:
mysite/
root directory is a container for your project
Best practice is to separate each feature with a new app
python manage.py startapp myapi
To link the myapi to the project
edit : mysite/settings.py
I am going to migrate the current structure to the DB. The default DB is SQLite provided by the Django integrated.
python manage.py migrate
django provides a admin panel. Let’s build credential for that:
python manage.py createsuperuser
After giving the credentials the user is created:
Now we can restart the app and visit localhost:8000/admin with the cred
Let’s create our new model
I have added this class in,
class Employee(models.Model):
name = models.CharField(max_length=60)
profession= models.CharField(max_length=60)
def __str__(self):
return self.name
EVERYTIME YOU CREATE A MODEL NEED TO DO MIGRATION
python manage.py makemigrations
Migrations for ‘myapi’:
myapi\migrations\0001_initial.py
— Create model Employee
Add it to admin pannel
from django.contrib import admin
from .models import Employee
# Register your models here.
admin.site.register(Employee)
Found issue adding new Employee
Then found solution python manage.py migrate --run-syncdb
Now setting up django rest framework
$ pip install djangorestframework
It is already there
adding it to setting
INSTALLED_APPS = [
…
‘rest_framework’,
]
Creating a serializer file in myapp
# serializers.py
from rest_framework import serializers
from .models import Employee
class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Employee
fields = ('name', 'profession')
update views.py for fetching
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import EmployeeSerializer
from .models import Employee
# Create your views here.
class EmployeeViewSet(viewsets.ModelViewSet):
queryset = Employee.objects.all().order_by('name')
serializer_class = EmployeeSerializer
Let’s create routing:
let’s visit url.py
from django.contrib import admin
from django.urls import include, path
from rest_framework import routers
#from . import views
from myapi import views
router = routers.DefaultRouter()
router.register(r'employees', views.EmployeeViewSet)
urlpatterns = [
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
After running the server:
Conclusion:
In this video I just straightforwardly covered the db fetching and serialization only. Initially looks fine and easy but not sure about all the important patterns like repository or services (Business layers).