Creating Django Models and Views

Creating Django Models

In Django, Models are classes that deal with databases in an object-oriented way. Each model class refers to a database table and each attribute in the model class refers to a database column. Here, we will create an Employee model and EmployeeTask model in Django. The EmployeeTask model holds a ManyToOne relationship with the Employee model  We require the following attributes for our Employee entity:

  • emp_id
  • name
  • gender
  • designation

The attributes for our EmployeeTask model as follows:

  • task_name
  • employee (foreign key – Employee)
  • task_desc
  • created_date
  • deadline

Let’s get into the implementation of the Employee model in Django. You can replace the models.py Python file with the below code:

Python3




GENDER_CHOICES = (('M','Male'),
                      ('F','Female'),)
  
class Employee(models.Model):
    emp_id = models.IntegerField()
    name = models.CharField(max_length=150)
    gender = models.CharField(max_length=1,
                              choices=GENDER_CHOICES,
                              default='M')
    designation = models.CharField(max_length=150)
  
    class Meta:
        ordering=('emp_id',)
  
    def __str__(self):
        return self.name


The Employee model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class.  It has an ordering attribute that orders the result in an ascending order based on employee id.

Next, let get into the implementation of EmployeeTask Model. You can add the below code to the models.py file.

Python3




class EmployeeTask(models.Model):
    task_name = models.CharField(max_length=150)
    employee = models.ForeignKey(Employee,
                                  related_name='tasks',
                                  on_delete=models.CASCADE)
    task_desc = models.CharField(max_length=350)
    created_date = models.DateTimeField(auto_now_add=True)
    deadline = models.DateTimeField()
  
    class Meta:
        ordering = ('task_name',)
  
    def __str__(self):
        return self.task_name


The EmployeeTask model is a subclass of the django.db.models.Model class and defines the attributes and a Meta inner class.  It has an ordering attribute that orders the result in an ascending order based on task_name. It has an employee field that holds a many-to-one relationship with the Employee model.

employee = models.ForeignKey(Employee,
                                  related_name='tasks',
                                  on_delete=models.CASCADE)

The related_name helps in a reverse relationship. Reverse relationship means referring from Employee to EmployeeTask. The employee field represents the Employee model in the EmployeeTaks. Likewise, the  related_name represents the EmployeeTask in the Employee model.

Reverse relations are not automatically included by the serializer class. We must explicitly add it to the field list. If you set an appropriate related_name argument on the relationship, then you can use it as a field name (You will be able to understand reverse relation while serializing the Models). 

Let’s make the initial migrations using the below command.

python manage.py makemigrations

If the migration is a success then apply all generated migrations using the below command:

python manage.py migrate

If successful you can check your database entries. Now, let’s create the Django views.

Creating Views

Django views facilitate processing the HTTP requests and providing HTTP responses. On receiving an HTTP request, Django creates an HttpRequest instance and it is passed as the first argument to the view function. The view function checks the value and executes the code based on the HTTP verb. Here the code uses @csrf_exempt decorator to set a CSRF (Cross-Site Request Forgery) cookie. This makes it possible to POST to this view from clients that won’t have a CSRF token.

You can add the below code to your view.py file. 

Python3




from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
  
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
  
from employees.models import Employee, EmployeeTask
from employees.serializers import EmployeeSerializer, EmployeeTaskSerializer
  
  
@csrf_exempt
def employee_list(request):
    if request.method == 'GET':
        emp = Employee.objects.all()
        emp_serializer = EmployeeSerializer(emp, many=True)
        return JsonResponse(emp_serializer.data, safe=False)
  
    elif request.method == 'POST':
        emp_data = JSONParser().parse(request)
        emp_serializer = EmployeeSerializer(data=emp_data)
          
        if emp_serializer.is_valid():
            emp_serializer.save()
            return JsonResponse(emp_serializer.data,
                                status=201)
        return JsonResponse(emp_serializer.errors,
                            status=400)
  
@csrf_exempt
def employee_detail(request, pk):
    try:
        emp = Employee.objects.get(pk=pk)
    except Employee.DoesNotExist:
        return HttpResponse(status=404)
  
    if request.method == 'GET':
        emp_serializer = EmployeeSerializer(emp)
        return JsonResponse(emp_serializer.data)
    elif request.method == 'DELETE':
        emp.delete()
        return HttpResponse(status=204)
  
  
@csrf_exempt
def employeetask_list(request):
    if request.method == 'GET':
        emptask = EmployeeTask.objects.all()
        emptask_serializer = EmployeeTaskSerializer(emptask, many=True)
        return JsonResponse(emptask_serializer.data, safe=False)
    elif request.method == 'POST':
        emptask_data = JSONParser().parse(request)
        emptask_serializer = EmployeeTaskSerializer(data=emptask_data)
        if emptask_serializer.is_valid():
            emptask_serializer.save()
            return JsonResponse(emptask_serializer.data,
                                status=201)
        return JsonResponse(emptask_serializer.errors,
                            status=400)
  
@csrf_exempt
def employeetask_detail(request, pk):
    try:
        emptask = EmployeeTask.objects.get(pk=pk)
    except EmployeeTask.DoesNotExist:
        return HTTPResponse(status=404)
  
    if request.method == 'GET':
        emptask_serializer = EmployeeTaskSerializer(emptask)
        return JsonResponse(emptask_serializer.data)
      
    elif request.method == 'DELETE':
        emptask.delete()
        return HttpResponse(status=204)


Here, we have different functions to process requests related to the Employee model and EmployeeTask model — employee_list, employeetask_list, and employee_detail and employeetask_detail. The employee_list and employeetask_list functions are capable of processing requests to retrieve all employees and employee’s tasks or to create a new employee and create a new employee task. The employee_detail and employeetask_detail functions are capable of processing requests such as retrieve a particular entry and delete an entry.

Setting URL Configuration

Now, it’s necessary to route URLs to view. You need to create a new Python file name urls.py in the app (employees) folder and add the below code.

Python3




from django.urls import path
from employees import views
  
urlpatterns = [
    path('employees/',
        views.employee_list,
        name = 'employee-list'),
    path('employees/<int:pk>/',
        views.employee_detail,
        name='employee-detail'),
    path('task/',
        views.employeetask_list,
        name = 'employeetask-list'),
    path('task/<int:pk>/',
        views.employeetask_detail,
        name='employeetask-detail'),


Based on the matching path the URLs are routed to corresponding views. Next, we have to replace the code in the urls.py file in the root folder (emt\emt\urls.py). At present, it has the root URL configurations. Update the urls.py file with the below code.

Python3




from django.urls import path, include
  
urlpatterns = [
    path('', include('employees.urls')),
]


Serializer Relations – Django REST Framework

Serialization is one of the most important concepts in RESTful Webservices.  It facilitates the conversion of complex data (such as model instances) to native Python data types that can be rendered using JSON, XML, or other content types. In Django REST Framework, we have different types of serializers to serialize object instances, and the serializers have different serializer relations to represent model relationships. In this section, we will discuss the different serializer relations provided by Django REST Framework Serializers. 

Table of Contents

  • Getting Started
  • Creating Django Models and Views
  • PrimaryKeyRelatedField
  • StringRelatedField
  • SlugRelatedField
  • HyperlinkedIndetityField
  • HyperlinkedRelatedField
  • Nested Relationship

Similar Reads

Getting Started

Before working on Django REST Framework serializers, you should make sure that you already installed Django and Django REST Framework in your virtual environment. You can check the below tutorials:...

Creating Django Models and Views

Creating Django Models...

PrimaryKeyRelatedField

...

StringRelatedField

...

SlugRelatedField

...

HyperlinkedIndetityField

...

HyperlinkedRelatedField

...

Nested Relationship

PrimaryKeyRelatedField represents the target of the relation using the primary key (pk). It can be achieved by generating the relationship using the rest_framework.serializers.PrimaryKeyRelatedField() field. By default, this field is read-write, but you can make it read-only by setting the read_only attribute to True. The PrimaryKeyRelatedField has the following arguments:...

Contact Us