Home » Home » Django Models

In Django, a model is a Python class that defines the structure and behavior of data in your application. Models are used to create and manipulate data in the database, as well as to validate and clean data before it is saved. In this article, we will introduce you to Django models and show you how to create and use them in your applications.

Creating a Model

To create a model, you need to define a Python class that inherits from django.db.models.Model. The class attributes represent the fields of the model.

For example, here’s a simple model for a blog post:

from django.db import models

class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField('date published')

In this model, we have defined three fields: title, body, and pub_date. The title field is a CharField with a maximum length of 200 characters. The body field is a TextField that can hold a large amount of text. The pub_date field is a DateTimeField that stores the date and time when the post was published.

Each field is represented by a specific type of Django model field. Django provides many built-in field types, such as CharField, TextField, DateTimeField, BooleanField, and many others.

Creating a Database Table

After defining a model, you need to create a database table to store the data. Django provides a built-in command called migrate that creates database tables based on the models defined in your application.

To run the migrate command, open your command prompt or terminal and navigate to your project directory. Then run the following command:

python manage.py migrate

This command will create the necessary tables in the database for all the models defined in your application.

Creating and Updating Records

To create a new record in the database, you need to create an instance of the model and save it to the database. For example, to create a new blog post, you can do the following:

from myapp.models import Post
from django.utils import timezone

post = Post(title='My First Blog Post', body='Hello, world!', pub_date=timezone.now())
post.save()

In this example, we have created a new instance of the Post model and set the title, body, and pub_date fields. We have then called the save() method to save the record to the database.

To update an existing record, you can simply modify the fields of the instance and call the save() method again.

Querying Records

To retrieve records from the database, you can use Django’s built-in ORM (Object-Relational Mapping) system. The ORM allows you to write Python code to interact with the database, rather than writing SQL queries directly.

For example, to retrieve all the blog posts from the database, you can do the following:

from myapp.models import Post

posts = Post.objects.all()

In this example, we have used the objects attribute of the Post model to retrieve all the records from the database. The all() method returns a queryset object that can be used to filter and manipulate the data.

Filtering Records

You can filter the queryset to retrieve only the records that meet certain conditions. For example, to retrieve all the blog posts that were published in the last week, you can do the following:

from myapp.models import Post
from django.utils import timezone

posts = Post.objects.filter(pub_date__gte=timezone.now() - timezone.timedelta(days=7))

In this example we have used the filter() method to retrieve only the records that meet the condition specified in the argument. The pub_date__gte argument specifies that we want to retrieve only the records where the pub_date field is greater than or equal to the current date and time minus seven days.

You can also use other lookup methods to filter the queryset, such as exact, contains, startswith, endswith, and many others.

Deleting Records

To delete a record from the database, you can call the delete() method on the instance. For example, to delete a blog post, you can do the following:

from myapp.models import Post

post = Post.objects.get(pk=1)
post.delete()

In this example, we have used the get() method to retrieve the blog post with the primary key of 1. We have then called the delete() method to delete the record from the database.

Conclusion

Django models provide a convenient way to define and manipulate data in your application. By using models, you can create a schema for your database, validate and clean data before it is saved, and query and manipulate the data using Python code. We hope this article has given you a good introduction to Django models and how to use them in your application

Related Posts

Leave a Reply

%d bloggers like this: