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

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 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.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 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.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.

Django Forms

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. It...

3 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

How to Uninstall Django from cmd

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 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 Celery

Django is a python-based web framework. It is an open-source and free-to-use framework. Django uses the Model View Template architecture. Django provides many functionalities to web developers. One of these...

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.

Creating View in Django

Creating View in Django    Django views are a key component of the frameworkbased applications.We are using Python function or class at their simplest, which takes up a web query and returns a web response.Views are used to get objects from the server, change objects if needed, render types, return HTML, and much more. Class Based View and Function based Django has two types of views: views based on functions (FBVs) and views based on class (CBVs).Initially, Django began with only FBVs, but then introduced CBVs as a way to model features so we didn't have to write boilerplate (i.e. the same software) code again and again.CBVs would be a way to increase efficiency, so you don't have to write as much code as you can. CBVs are classes of Python at their heart. Django ships with a range of "model" CBVs with pre-configured features that can be reused and often expanded.Then helpful names are given to these classes that explain what kind of functionality they provide.These are often referred to as "universal views" because they provide solutions to specific needs. The classes have a journal View function, or "view" for short, is simply a Python program that uses a web query and returns a web response. This response may include the HTML content of a web page, or a redirect, or a 404 error, or an XML file, or an image, etc. Example: You use a view to create a web page, remember that you need to connect a view to a URL to see it as a web page. Simple View We will create a simple view in myapplication to say “Welocome to django application” See the following view – from django.http import HttpResponse ...

4 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 Class Based Views

Class-based views were developed to solve the problem of customizing function-based generic views. We can arrange our view code Object-Oriented by using class views. Class-based views do more than function-based...

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 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 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 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 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.

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.