Django Models

Defining models for database tables:

models are Python classes that represent database tables.

You can define your models in the models.py file of your Django app.

Each model class corresponds to a table in your database, and each attribute of the class represents a column in that table.


For example, let's say you're building a blog application. You might define a Post model like this:

                                
from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)
                                                         
                                
                            

In this example, we define a Post model with three fields: hash, attribute, and created field. The structure of our product described as the Post will mirror the database table with columns for each field.

Working with Django ORM (Object-Relational Mapping):

Django’s ORM is an intuitive, easy-to-use way of interacting with databases. Instead of writing raw SQL queries, you can create, retrieve, update and delete objects using the familiar Python language.

For example, to create a new Post object and save it to the database:

                                
from myapp.models import Post

# Create a new post object
new_post = Post(title="My First Post", content="This is the content of my first post.")

# Save the post to the database
new_post.save()
                  
                                
                            

To retrieve objects from the database:

                                
# Retrieve all posts
all_posts = Post.objects.all()

# Retrieve a specific post by its primary key
post = Post.objects.get(pk=1)
                                
                            

To update an existing object:

                                
# Retrieve a post
post = Post.objects.get(pk=1)

# Update its attributes
post.title = "Updated Title"
post.save()

                                
                            

To delete an object:

                                
# Retrieve a post
post = Post.objects.get(pk=1)

# Delete the post
post.delete()
                                
                            

Django's ORM handles the translation between Python objects and database records, making it easier and safer to work with your database in Django applications.

Hey there! Let's go for Learn fasta then! It is more than just coding; it is to have the superpower that can solve any problem. Through simple and easy-to-grasp examples you will sail through the learning process. In addition, it is not just about coding– you will acquire competencies on how to solve complex problems, analyze data, and come up with efficient solutions. Shall we start this wonderful journey together! learnfasta.com terms of use, Copyright 2025 All Rights Reserved.