Home >>Django Tutorial >Django Model

Django Model

Django Model

In Django, a model is a class that represents a table or collection in our Database. It contains the essential fields and methods. Each model class gets mapped to a single table in the database.

Django Model is a subclass of django.db.models.Model and every attribute of the class represents a field of the table or collection.

Django provides a database-abstraction API that allows us to create, retrieve, update, and delete a record from the mapped table.

The Model is defined in theModels.py file and it can contain multiple models.

	
from django.db import models  
  
class Employee(models.Model):  
    first_name = models.CharField(max_length=30)  
    last_name = models.CharField(max_length=30)
      

Now, the SQL command of the given this model will look like below.

CREATE TABLE appname_employee (
"id" INT NOT NULL PRIMARY KEY,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL);

This table contains an auto-created id field, the name of the table is a combination of app name and model name that can be changed further.

Manipulating Data (CRUD)

Now we will create a "crud" view to see how we can do CRUD operations on Django models. Our myapp/views.py will look like this −

myapp/views.py


from myapp.models import Dreamreal
from django.http import HttpResponse

def crud (request):

   dreamreal = Dreamreal(
      website = "www.jerry.com", mail = "[email protected]", 
      name = "jerry", phonenumber = "9955995599"
   )
   
   dreamreal.save()
   
   #Read ALL entries
   objects = Dreamreal.objects.all()
   res ='Printing all entries in the DB : <br>'
   
   for elt in objects:
      res += elt.name+"<br>"
   
   #Read a specific entry:
   jerry = Dreamreal.objects.get(name = "jerry")
   res += 'Printing One entry <br>'
   res += jerry.name
   
   #Delete an entry
   res += '<br> Deleting an entry <br>'
   jerry.delete()
   
   #Update
   dreamreal = Dreamreal(
      website = "www.jerry.com", mail = "[email protected]", 
      name = "jerry", phonenumber = "123456"
   )
   
   dreamreal.save()
   res += 'Updating entry<br>'
   
   dreamreal = Dreamreal.objects.get(name = 'jerry')
   dreamreal.name = 'Abhi'
   dreamreal.save()
   
   return HttpResponse(res)