Django Models

Django Models

A model is a representation of tables or collections present in a database. This model makes sure that every attribute of the class denotes a field of the table or the collection. All the models are defined under the app/ file. As per our example, all the models will fall under myapp/ file.

Also Read: Django Page Redirection

How to Create A Model?

Here, we will help you to understand the creation of a model with the help of Dreamreal model.

Ensure that all your models inherit its properties from django.db.models.Model.

In the above example, you can see that Dreamreal model consists of four attributes which will act as the fields of the table. These four attributes are

S.No. Attribute Type of Field
1 website Character Field
2 mail Character Field
3 name Character Field
4 phonenumber Integer Field


The Meta class helps in naming your database or collection. It is done with the help of the db_table attribute. In the above example, the name of the database is dreamreal. Django lets you name your database or collection automatically by using myapp_modelName. This class will help you to forcibly name a table as per your interest.

There are a number of other field types available in django.db.models. You can take a look at them over here:

Once you are done with the model creation, you are required to run the following command to generate the actual database:

$python syncdb

Manipulation of Data (CRUD – Create, Read, Update, Delete)

In this section, we will help you to understand the CRUD operations on models by creating a crudops view. The myapp/ file contains the following content:


from myapp.models import Dreamreal

from django.http import HttpResponse

def crudops(request):

  #Creating an entry

  dreamreal = Dreamreal(

     website = “”, mail = “[email protected]”,

     name = “sorex”, phonenumber = “002376970”


  #Read ALL entries

  objects = Dreamreal.objects.all()

  res =’Printing all Dreamreal entries in the DB : <br>’   

  for elt in objects:

     res +=”<br>”

  #Read a specific entry:

  sorex = Dreamreal.objects.get(name = “sorex”)

  res += ‘Printing One entry <br>’

  res +=

  #Delete an entry

  res += ‘<br> Deleting an entry <br>’



  dreamreal = Dreamreal(

     website = “”, mail = “[email protected]”,

     name = “sorex”, phonenumber = “002376970”


  res += ‘Updating entry<br>’

  dreamreal = Dreamreal.objects.get(name = ‘sorex’) = ‘thierry’

  return HttpResponse(res)


Other Data Manipulation

Data can be manipulated in other ways also. Always remember that CRUD operations are performed on the instances of the model while all the operations which will be covered here fall directly under the class representation of the model.

To understand this more clearly, we will be creating a datamanipulation view in myapp/ file.

from myapp.models import Dreamreal

from django.http import HttpResponse

def datamanipulation(request):

  res = ”  

  #Filtering data:

  qs = Dreamreal.objects.filter(name = “paul”)

  res += “Found : %s results<br>”%len(qs)  

  #Ordering results

  qs = Dreamreal.objects.order_by(“name”)  

  for elt in qs:

     res += + ‘<br>’  

  return HttpResponse(res)

Linking Models

Django ORM provides three methods via which you can link models.

* One-to-one relationships

* One-to-many relationships

* Many-to-many relationships

One-to-many relationships

In the above provided example, Dreamreal has the options to have various online websites. This is achieved with the help of django.db.models.ForeignKey. Take a look at the following example:


from django.db import models

class Dreamreal(models.Model):

  website = models.CharField(max_length = 50)

  mail = models.CharField(max_length = 50)

  name = models.CharField(max_length = 50)

  phonenumber = models.IntegerField()

  online = models.ForeignKey(‘Online’, default = 1)

  class Meta:

     db_table = “dreamreal”

class Online(models.Model):

     domain = models.CharField(max_length = 30)

  class Meta:

     db_table = “online”

In the updated file of myapp/, we have included the online model and then linked this file to the Dreamreal model.


In the below section, we will take a look at how the linking process works with the help of shell. To do so, we need to start by creating a few of the entries under Dreamreal company. This is just for testing purpose, which will be performed in the Django shell.

$python shell

>>> from myapp.models import Dreamreal, Online

>>> dr1 = Dreamreal()

>>> = ‘’

>>> = ‘company1’

>>> dr1.mail = ‘[email protected]

>>> dr1.phonenumber = ‘12345’


>>> dr2 = Dreamreal()

>>> = ‘’

>>> = ‘’

>>> = ‘company2’

>>> dr2.mail = ‘[email protected]

>>> dr2.phonenumber = ‘56789’


Following are a few of the hosted domains:

>>> on1 = Online()

>>> = dr1

>>> on1.domain = “”

>>> on2 = Online()

>>> = dr1

>>> on2.domain = “”

>>> on3 = Online()

>>> on3.domain = “”

>>> dr2 = Dreamreal.objects.all()[2]

>>> = dr2




The given command will help you to access the attribute of the Dreamreal company. This retrieval is done from an online domain.


And for the list of all the online domains hosted by Dreamreal company, you need to type in the following command:

>>> dr1.online_set.all()

You need to use manipulating methods (such as filter, all, exclude, order_by, etc.) to get a QuerySet.

To perform filter operations, you can also access linked model attributes. The following command lets you retrieve all the online domains where the Dreamreal contains keyword as ‘company’.

>>> Online.objects.filter(company__name__contains = ‘company’

Well, you should know that this kind of keyword specific search query is applicable on the SQL database only. It will definitely not work for any non-relational database where there is no scope for joints.

As mentioned above, there are two more ways in which you can link models. In a one-to-one relationship, the relation between two objects guarantees a unique link. If such a case imposed on the above example then it will allow only one online entry for each and every Dreamreal entry.

The many-to-many relationship lets the user link two tables. This last linking model is applicable to SQL based database only.