Django Models - Django Models Fields | W3school

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/models.py file. As per our example, all the models will fall under myapp/models.py 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

[post_middile_section_ad]

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: https://docs.djangoproject.com/en/2.1/topics/db/models/#field-types.

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

$python manage.py 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/views.py file contains the following content:

myapp/views.py

from myapp.models import Dreamreal

from django.http import HttpResponse

def crudops(request):

  #Creating an entry

  dreamreal = Dreamreal(

     website = “www.polo.com”, mail = “sorex@polo.com”,

     name = “sorex”, phonenumber = “002376970”

  )

  dreamreal.save()

  #Read ALL entries

  objects = Dreamreal.objects.all()

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

  for elt in objects:

     res += elt.name+”<br>”

  #Read a specific entry:

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

  res += ‘Printing One entry <br>’

  res += sorex.name

  #Delete an entry

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

  sorex.delete()  

  #Update

  dreamreal = Dreamreal(

     website = “www.polo.com”, mail = “sorex@polo.com”,

     name = “sorex”, phonenumber = “002376970”

  )

  dreamreal.save()

  res += ‘Updating entry<br>’

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

  dreamreal.name = ‘thierry’

  dreamreal.save()

  return HttpResponse(res)

[post_middile_section_ad]

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/views.py 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 += elt.name + ‘<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:

myapp/models.py

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/models.py, we have included the online model and then linked this file to the Dreamreal model.

[post_middile_section_ad]

In the below section, we will take a look at how the linking process works with the help of manage.py 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 manage.py shell

>>> from myapp.models import Dreamreal, Online

>>> dr1 = Dreamreal()

>>> dr1.website = ‘company1.com’

>>> dr1.name = ‘company1’

>>> dr1.mail = ‘contact@company1’

>>> dr1.phonenumber = ‘12345’

>>> dr1.save()

>>> dr2 = Dreamreal()

>>> dr1.website = ‘company2.com’

>>> dr2.website = ‘company2.com’

>>> dr2.name = ‘company2’

>>> dr2.mail = ‘contact@company2’

>>> dr2.phonenumber = ‘56789’

>>> dr2.save()

Following are a few of the hosted domains:

>>> on1 = Online()

>>> on1.company = dr1

>>> on1.domain = “site1.com”

>>> on2 = Online()

>>> on2.company = dr1

>>> on2.domain = “site2.com”

>>> on3 = Online()

>>> on3.domain = “site3.com”

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

>>> on3.company = dr2

>>> on1.save()

>>> on2.save()

>>> on3.save()

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

>>> on1.company.name

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.