Django Model

Django Model

A template is a class representing a table or collection in our DB and where each class attribute is a table or collection area. In the app / models.py, models are described (in our example: myapp / models.py)

Model is defined in Models.py file. This file can contain multiple models.

Creating a Model

from django.db import models
class Django(models.Model):
   website = models.CharField(max_length = 20)
   mail = models.CharField(max_length = 10)
   first_name = models.CharField(max_length=30) 
   last_name = models.CharField(max_length=30) 
   class Meta:
      db_table = “Django" 

The first_name and last_name fields are specified as class attributes and each attribute maps to a database column.

The model will create a table look like this.

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

Django Model Field.

Field Name Class Particular
AutoField Class field(option) It is an integer field and it increment automatically.
BigAutoFeild Class BigAutofield(option) It is same as like Autofield. It is 64bit integer, that guarantees to fit a number from 1 to 9223372036854775807    
BigIntegerfield Class BigIntegerField It is also 64bit  integer, It guarantees to fit number from -9223372036854775808 to 9223372036854775807
BinaryField Class BinaryField It is used to store binary raw data.
CharField Class DateField(auto_now=False,auto_now_add=false) It is used to represent datetime.date instance in python language.
BooleanField Class BooleanField A domain true / false. A CheckboxInput is the default form widget for this area.
DateTimeField Class DateTimeField(auto_now=False,auto_now_add=False) It is used for date and time, a datetime.datetime instance is defined in Python.
DecimalField Class DecimalField(max_digits=None, decimal_places=None) It is a decimal number of fixed-precision, represented by a Decimal example in Python.
DurationField Class DurationField(**option) This field is used for storing periods of time
EmailField Class EmailField(max_length=254) It is a CharField that searches for a valid email address to be the value.
FileField Class FileField(upload_to=None,max_length=100) It is file-upload field
FloatField Class FloatField(**option) It is a number of floating-points defined by a float instance in Python.
ImageField Class ImageField(upload_to=None,height_field=None,width_field=None,max_length=100) It inherits all FileField attributes and methods, but also validates that a valid image is the uploaded object.
IntegerField Class IntegerField(**option) It's a domain of integer. In all Django-supported databases, values from -2147483648 to 2147483647 are free.
NullBooleanField Class NullBooleanField(option) It is like a BooleanField, but only allows Null as one of the option.
PositiveIntegerField Class PositiveIntegerField(option) Like an IntegerField, but it must either be positive or zero (0). Values between 0 and 2147483647 are safe in all Django-based databases.
TextField Class TextField(otion) It is wide area for text.
TimeField class TimeField(auto_now=False,auto_now_add=False) A time, defined by a datetime.time example in Python.

Manuplating Data (CRUD)

Let's create a "crudops" view to see how we can perform CRUD operations on models. Our myapplication/views.py will look this while performing CRUD operation.

myapplication/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 = "=sum", phonenumber = "123456789"
   )
   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 += sum.name
  #Delete an entry
   res += '<br> Deleting an entry <br>'
   sorex.delete()
   #Update
   dreamreal = Dreamreal(
      website = "www.sum.com", mail = "sum@polo.com",
      name = "sum", phonenumber = "123456789"
   )
   dreamreal.save()
   res += 'Updating entry<br>'
   dreamreal = Dreamreal.objects.get(name = 'sum')
   dreamreal.name = 'thierry'
   dreamreal.save()
   return HttpResponse(res) 

Other Manuplation Data

Let's discuss other design and manipulation operations that we can do. Note that the CRUD operations were done on our model's instances, now we're going to work directly with the model's class.

Creating ‘datamanuplation’ view in myapplication/views.py

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("phone")
   for elt in qs:
    res += elt.name + '<br>'
return HttpResponse(res) 

Linking Models

It is used in 3 ways to link:

In first case we will show one-to-many relationships. As you can see in the below example. Most company can have multiple websites online. Use django.db.models.ForeignKey to describe the relationship

myapplication/model.py

from django.db import models
class Dreamreal(models.Model)
   websitename = models.CharField(max_length = 50)
   mailid = models.CharField(max_length = 60)
:
   firstname = models.CharField(max_length = 60)
   phonenumber = models.IntegerField()
   online = models.ForeignKey('Online', default = 1)
   class Meta:
      db_table = "dreamreal"
class Online(models.Model):
      domain = models.CharField(max_length = 20)
   class Meta:
  db_table = "online" 

Let's check how all of this is working via manage.py shell –

Creating some companies (Dreamreal entries) for testing in our Django shell –

python manage.py shell
>>> from myapplication.models import Dreamreal, Online
>>> dr1 = Dreamreal()
>>> dr1.website = 'company1.com'
>>> dr1.name = 'company1'
>>> dr1.mail = 'dream@company1'
>>> dr1.phonenumber = '12385945'
>>> dr1.save()
>>> dr2 = Dreamreal()
>>> dr1.website = 'company2.com'
>>> dr2.website = 'company2.com'
>>> dr2.name = 'company2'
>>> dr2.mail = 'dream@company2'
>>> dr2.phonenumber = '1236989'
>>> dr2.save() 

Some Hosted Domain

>>> 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() 

It is easy to access the hosting company's attribute from an online domain

>>> on1.company.name

And if we want to learn all the online territory of a client in Dreamreal, we're going to use this code

>>> dr1.online_set.all()

Note that all the manipulative methods that we've seen before (filter, all, exclude, order by ...) is to get a QuerySet.

You can also access the related template attributes for filtering operations, let's say you want to get all online domains where the name of Dreamreal includes ' business '


>>> Online.objects.filter(company__name__contains = 'company'

For SQL DB, this kind of query is only supported. It will not work for non-relational DB where there are no joins and there are two ' .'

But this is not the only way models can be connected, you also have OneToOneField, a connection that ensures the unique relationship between two objects. In our example above, if we use the OneToOneField, it means only one Online entry is possible for each Dreamreal entry and the other way.

And the last one, the tables relationship ManyToManyField (n-n). Note that these are relevant to DB based on SQL.


Related Topics

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

Django CMS vs WordPress

Both Django CMS and WordPress belong "Self-Hosted Blogging" or "Content Management System (CMS)" category, that is used to manage digital content. Bloggers usually use these platforms. Django CMS Django is one of...

4 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Django Authentication

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Django Model Fields

In Django, if we want to store the information about anything, we use Models. It contains various fields about the data. Generally, each model represents a database where all the...

4 minutes read.

Django DRF

Django Rest Framework, which is also referred to as DRF, is a very powerful application to build RESTful APIs in a Django application. DRF uses the Django framework. Similar to...

3 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django Project

Django Project Let's start to use it. Each web app you want to build in Django is called a project; and a project is a collection of apps. A software is a series of...

3 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

Best Django courses

In this tutorial, we will see various courses in python Django available on the internet. Django has become popular these days, so courses on it are also increasing day by...

7 minutes read.

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django Image Upload

Django is a python based web framework that uses Model View Template as its architecture. Django provides really quick web development with its functionalities. While we are building a website,...

3 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django ORM

Django is a Python web framework that enables easy and quick web development. Django has a handy and powerful feature called Django Object Relational Mapper, also known as Django ORM,...

3 minutes read.