Django Models

Filed Under: Django

In this tutorial, we’ll get into the details of Django Models. Before we do that, let’s quickly set up our Django Project from the terminal.

Execute the following commands one by one:


mkdir JournaldevDjangoModels
cd JournalDevDjangoModels
virtualenv -p /usr/local/bin/python3 env
source env/bin/activate
pip3 install django
django-admin startproject DjangoModel

django models project setup


python3 manage.py runserver
django-admin startapp school

django models example

Once we’ve created the school app, we need to add it in the INSTALLED_APPS inside the settings.py

django model app

Take note of the models.py file that’s created in the school app. It’ll be the Most Wanted file in this tutorial. Let’s get started.

Django Models

The database is an important part of any web application. Django Models are a source of information for your data. You can store values in the form of fields in it.

Each Django Model would be held in the database and the fields defined in the Django Models are database fields.

Django Models are used to execute SQL code behind the scene as well.

Let’s create our first Django Model in the models.py file.

Django Model Example

Following is the code from the models.py file:


from django.db import models

# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    email = models.EmailField()
    website = models.URLField()

Student is a Django Model with four fields.

Django Model Fields

Django Models can have any of the following types of fields CharField, IntegerField, EmailField, URLField, DateField, BooleanField, AutoField, UUIDField, OneToOneField, ManyToOneField.

How to set a primary key?


id = models.AutoField(
        primary_key=True,
    )

Field Options

max_length – Set the maximum number of characters allowed

verbose_name – human readable name of the field


full_name = models.CharField(verbose_name='full name', max_length=100)

null – Setting null equal to True allows us to leave the column as blank. The column would then store NULL as the value.

Example:


age = IntegerField(null=True)

blank – Again the field is allowed blank if blank=True. blank is used for Form validations where we can specify if entering in a field is mandatory or not.

choices – This is like a 2-tuple and is used to choose from a list of values.


from django.db import models

# Create your models here.
class Student(models.Model):
    SECTION = (
        ('A', 'Alpha'),
        ('B', 'Beta'),
        ('C', 'Cappa'),
    )
    name = models.CharField(max_length=30)
    age = models.IntegerField()
    email = models.EmailField()
    website = models.URLField()
    section = models.CharField(max_length=1, choices=SECTION, default=SECTION[1][0])

default field option is required in choices unless to put a null or blank option.

How to add this Model to the Database?


python3 manage.py makemigrations school

The above command creates the model.

This is the output from the terminal:

django model makemigrate

Let’s open the views.py file and create basic Django Models and print them on the screen.


from django.shortcuts import render
from school.models import Student
from django.http import HttpResponse
# Create your views here.


def home(request):
   #Creating an entry
   objects = Student.objects.all().delete()
   student = Student(name = "Anupam", email = "anupam@journaldev.com",age = "24", website = "www.journaldev.com",section="A")
   student.save()
   student = Student(name = "Another", email = "another@journaldev.com",age = "21", website = "www.google.com")
   student.save()
   objects = Student.objects.all()
   res ='Printing all Students entries in the DB : <br>'

   for elt in objects:
       res += "Name: "+elt.name+"<br>"
       res += "Age: "+str(elt.age)+"<br>"
       res += "Section: "+elt.section+"<br>"
       res += "Section Full Name: "+elt.get_section_display()+"<br>"


   return HttpResponse(res)

save() method adds the model to the database.

Every time when you load this page new model would get appended. Hence at the beginning, we delete() all models.

For the choices, to display the right-hand side part we use the auto-generated method get_section_display()

Indentation matters!

django model views

Time to do the URL routing in the urls.py file.

django model url conf

Now run the following two commands:


python3 manage.py migrate
python3 manage.py runserver

django model fields

CRUD Operations

Alternative way to create a new instance of Django Model:


anupam = Student.objects.create(name = "Anupam", email = "anupam@journaldev.com",age = "24", website = "www.journaldev.com",section="A")

Besides creating, deleting, retrieving which we have implemented till now, we can search the data as well using filters.


from school.models import Student
from django.http import HttpResponse

def randomFunctionFilter(request):
   res = ''
   
   object = Student.objects.filter(name = "Anupam")
   res += "Found : %s students<br>"%len(object)
   
   obj = Student.objects.order_by("age")
   
   for elt in obj:
      res += elt.name + '<br>'
   
   return HttpResponse(res)

How to Filter greater than and less than?


object = Student.objects.filter(age__lt 10)
object = Student.objects.filter(age__gt 20)

Updating the Data


student = Student.objects.get(name='Anupam')
student.age = 100
student.save()

student = Student.objects.get(name='Anupam')
student.delete()
A metaclass is an inner class we can define inside Django Models. We can specify the verbose_name of the Django Model class and default ordering field name, db table name etc.


from django.db import models

class Me(models.Model):
    size = models.IntegerField()

    class Meta:
        ordering = ["-size"]
        verbose_name = "m"
        verbose_name_plural = "meee"
        db_table = "Mytable"

ordering = ["-size"] orders in descending order

For the complete list of features refer here

Foreign Keys

Let’s create a new Django Model and add foreign key


class Teacher(models.Model):
    name = models.CharField(max_length=100)
    students = models.ManyToManyField(Student)
    user = models.ForeignKey('auth.User', on_delete=models.CASCADE)

    def __str__(self):
        return self.name

The str method defines a human-readable representation of the model that is displayed in the Django admin site and in the Django shell.

Foreign Key is linked to another class. This time a django inbuilt class.
on_delete field option tells what to do when the model is being deleted.

  • CASCADE: When the referenced object is deleted, also delete the objects that have references to it (When you remove a blog post, for instance, you might want to delete comments as well).
  • PROTECT: Forbid the deletion of the referenced object. To delete it you will have to delete all objects that reference it manually.
  • SET_NULL: Set the reference to NULL (requires the field to be nullable). For instance, when you delete a User, you might want to keep the comments he posted on blog posts, but say it was posted by an anonymous (or deleted) user.
  • SET_DEFAULT: Set the default value.

through

through is used to connect two tables through an intermediary class.
Let’s learn about this through an example use case.

Following is our models.py class:


from django.db import models

# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length=30)


class Teacher(models.Model):
    name = models.CharField(max_length=100)
    members = models.ManyToManyField(Student, through='Classroom')


class Classroom(models.Model):
    student = models.ForeignKey(Student, on_delete=models.CASCADE)
    teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
    date_joined = models.DateField()


Save the file and let’s run the following command in the terminal:


python3 manage.py makemigrations school
python3 manage.py migrate
python3 manage.py shell

This would open an interactive shell where we can create test data for the above Django Models.

django models shell output

django models shell output

We create sets of individual models and merge them in the classroom.
On querying the Teacher model, the students are automatically updated, thanks to through.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages