Django Models

What are Django Models?

Django models are a key part of the Django web framework, allowing developers to define the structure of their data. Models are Python classes that interact with a database, representing tables or collections. Each model attribute maps to a field in the corresponding table, defining the data that can be stored. These fields come in various types, like integers, strings, dates, or files. Django also provides options for nullability, default values, and relationships between different models.

Models are typically defined in a file called models.py within a Django application. Django automatically generates database tables based on the models, removing the need for manual SQL queries. Additionally, models support basic database operations such as creating, retrieving, updating, and deleting records.

Definition of Django Models

Django models are defined in the app/models.py file and play a crucial role in creating and managing database tables. These models inherit from django.db.models.Model, which provides essential attributes and methods for database interaction. The fields defined in the model class represent the columns of the associated database table.

When defining model attributes, various field types are available. For instance, CharField is used for strings, IntegerField for integers, and DateField for dates. These field types specify the kind of data that can be stored in each attribute and dictate the structure of the database table.

Model Class

The Model Class in Django acts as a blueprint for creating database tables, defining both the structure and behavior of the data. It abstracts the application's data from the database, allowing developers to work with Python objects instead of directly handling database queries.

A Model Class lets developers define table fields, including relationships like one-to-one, one-to-many, and many-to-many. It also supports custom managers for specialized database queries and operations, enabling more flexible data retrieval and modification.

Creating a Model Class in Django

To create a model class in Django:

1. Open your Django project in a text editor.

2. In the models.py file, import the necessary module:

from django.db import models

3. Define your model class, inheriting from models.Model. For example:

class YourModel(models.Model):    
		field1 = models.CharField(max_length=50)    
    field2 = models.IntegerField()    
    field3 = models.BooleanField(default=False)

4. Customize the fields by adding options like max_length or default.

5. Run the following commands to apply migrations:

python manage.py makemigrations
python manage.py migrate

This will create the database table corresponding to your model.

Structure and Syntax of a Model Class

A model class in Django consists of class declarations, attributes (representing fields), and methods. The attributes define the properties of the class, mapping to columns in the database. Some fields are required, such as the field name and data type, while others like maximum length or default values are optional.

For example, CharField stores strings, while IntegerField stores integers. Relationships between models can also be defined using fields like ForeignKey (many-to-one relationship) or ManyToManyField (many-to-many relationship).

Database Table

To create a database table for a model, follow these steps:

1. Open models.py in your Django app.

2. Define a class representing the model, for example:

class Member(models.Model):    
		firstname = models.CharField(max_length=255)    
    lastname = models.CharField(max_length=255)

3. Run migrations to create the database table:

python manage.py makemigrations
python manage.py migrate

Mapping Between Model Classes and Database Tables

In Django, each model class corresponds to a table in the database. Fields in the class map to columns in the table, and the field types determine the column types. This allows developers to interact with the database using Python objects.

Django also supports model inheritance, which enables child models to inherit fields and behaviors from parent models, encouraging code reuse and organization.

Field Types

Django offers several field types to define the data that can be stored. Some commonly used types include:

  1. CharField: Stores short strings.
  2. IntegerField: Stores integers.
  3. FloatField: Stores decimal numbers.
  4. DateField: Stores dates.
  5. DateTimeField: Stores date and time.
  6. BooleanField: Stores True or False.

For relationships, Django provides ForeignKey for many-to-one relationships and ManyToManyField for many-to-many relationships.

Class Attributes

In Django, class attributes define the characteristics and behaviors of a model. These include fields, relationships, and options like inheritance. For example, setting abstract = True makes a model abstract, meaning it can’t be instantiated but can be inherited by other models.

Django also supports multi-table inheritance and proxy models, which modify model behavior without creating new database tables.

By using these features, Django models offer a flexible way to define and manage database structures.

Create a free account to access the full topic

“It has all the necessary theory, lots of practice, and projects of different levels. I haven't skipped any of the 3000+ coding exercises.”
Andrei Maftei
Hyperskill Graduate