Know about Models in Django

Know about Models in Django

Introduction to Django models

In the process of learning Django, you surely will come across Django models. It is an important component of any Django application. Having good knowledge is essential to create an efficient web application using Django.

Django models define the fields and behavior of the data to be stored. Generally, a single model class defines a single table in the database. Models have fields that represent the columns of the table. We can also provide additional constraints to control what is stored.

How to define models

Django models are simply just classes that subclass django.db.models.Model. Each attribute of a model class is an instance of the appropriate Field class. The Field class determines the type of data stored, the minimum validation required and the widget which will be used while rendering the form field.

from django.db import models

class Manufacturer(models.Model):
  name = models.CharField(max_length=20)

  def __str__(self):
    return self.name


class Car(models.Model):
  model = models.CharField(max_length=20)
  year = models.PositiveIntegerField()
  manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)

In this code snippet, two models are declared namely Manufacturer and Car. The Manufacturer model has only one field which is name which can contain text of size at most 20 characters whereas the Car model has three fields, namely model that can contain text of size at most 20 characters, year field which can contain only positive integers and manufacturer field that references a Manufacturer in the Manufacturer table.

Various Fields for models

There are many different Field classes to store different types of data like integers, text, date, time and so on.

Here are some of the Field Classes

  • CharField - stores string data

  • IntegerField - stores integer

  • PositiveIntegerField - stores only positive integer

  • DataTimeField - stores date and time

  • DateField - stores only date

  • BooleanField - stores true/false value

  • DecimalField - stores numbers with a decimal point

  • EmailField - stores email

  • FileField - for storing file

  • TextField - for storing large text

  • ImageField - for storing images, and many more...

All Field classes have some common optional arguments. Here are some of them:

  • null - whether you want to allow storing null as a value, the default value is False

  • blank - when set to True it allows the field to be blank

  • choices - it allows you to have a value from a set of values. For using this option pass a list of 2-tuples to it with the first value of every tuple as the value you want to store and the second value as the display value that the user sees.

  • default - use it to give a default value to the field

  • primary_key - to use the field as a primary key for the model

  • unique - to apply the unique constraint to the field

Defining Relationships

Relating different tables to each other is a powerful feature of RDBMS. Django provides ways to implement different relations like one-to-one, many-to-one and many-to-many.

One-to-One relationship

To form an OneToOne relationship we use models.OneToOneField

from django.db import models

class User(models.Model):
    name = models.CharField(max_length=30)
    age = models.PositiveIntegerField()

class Profile(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    location = models.CharField(max_length=100)

Here we have defined a one-to-one relation between the user model and the profile model. Now in the database, we can store only a single Profile relating to a single user or vice versa.

Many-to-One relationship

To define a many-to-one relationship between two tables, we use models.ForeignKey(). It needs two parameters, first is the Model with which you want to create the relationship and the second is the on_delete positional argument to define the behavior of the model when the related record is deleted from the related table.

from django.db import models
class Author(models.Model):
    name = models.CharField(max_length=30)
    country = models.CharField(max_length=40)


class Book(models.Model):
    title = models.CharField(max_length=60)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

Here in the above snippet, we have defined two Models viz. Author and Book. Many-to-One relation defined in Book will allow an Author to have multiple 'Books' but no 'Book' can have more than one Author.

Many-to-Many relationship

For creating Many-to-many relationship, we use models.ManyToManyField(). It takes in another model as an argument to form a relationship. While defining a many-to-many relationship, you don't need to define the relation in both models just define it in one model.

from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=50)
    age = models.PositiveIntegerField()


class Course(models.Model):
    title = models.CharField(max_length=50)
    students = models.ManyToManyField(Student)

Now a student can have multiple courses and a course can have multiple students. For more in-depth information regarding ManyToManyField follow this link to the Django documentation

Conclusion

For developing a decent application using RDBMS, it is really important to have good knowledge of different types of relationships. Being good with RDBMS concepts will help you manage data efficiently. It is not much important what you are using but how you are using it. Keep learning keep building stuff.

In the next blog, we are going to see how to perform queries using the automatically-generated database-access API.

#Follow for more Django content

Did you find this article valuable?

Support Rishabh Kumar Bahukhandi by becoming a sponsor. Any amount is appreciated!