Django Model

A Django Model is a Python class used in the Django framework to define your application’s data structure and behavior. Models represent the database schema and act as the interface for interacting with your database. They allow you to perform CRUD (Create, Read, Update, Delete) operations easily and abstract the complexities of raw SQL queries.

Important Features of Django Models

1. Data Representation:

Each model represents a single table in the database.

Each attribute of the model corresponds to a column in the table.

2. Automatic Table Creation:

Django automatically creates a database table for each model when you run database migrations.

3. Field Types:

Django provides various field types (e.g., CharField, IntegerField, DateField) to define the type of data stored in each column.

Example:


from django.db import models
# This defines your table
class User(models.Model):
    name= models.CharField(max_length=200)  # A text column with max 100 characters
    address= models.TextField()  # A large text column
    created_at = models.DateTimeField(auto_now_add=True) # A column for date and time

 # A method to show a user name
  def __str__(self):
        return self.name

Process flow

1. When you create a model like this:

  • Django understands it as a database table.
  • The table will be called something like appname_user.

2. Attributes like name, address, and created_at become database columns with specific types:

  • CharField becomes a short text column.
  • TextField becomes a large text column.
  • DateTimeField is for storing date and time.

3. Django will create the table automatically when you run:


python manage.py makemigrations
python manage.py migrate

How to use a Model in your App?

You can add or retrieve user like this:

Adding a User:


# Import the model
from myapp.models import User

# Create a new user 
new_user = User(name="John", address="47 W 13th St, New York", published_date="2024-01-01 10:00")
new_user.save()  # Save to the database

Retrieving a User:


# Get all Users
all_users = User.objects.all()

# Print each title
for user in all_users :
    print(user.name)