Technology Encyclopedia Home >How to define and use models in Django?

How to define and use models in Django?

In Django, a model is a Python class that represents a database table. It defines the fields and behaviors of the data you want to store. Models are used to interact with the database, perform CRUD (Create, Read, Update, Delete) operations, and enforce data integrity.

Defining a Model

To define a model in Django, you create a subclass of django.db.models.Model and define fields as class attributes. Each field represents a column in the database table.

Here's an example of a simple model:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()
    price = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return self.title

In this example:

  • title, author, and published_date are defined using Django's built-in field types.
  • price uses DecimalField to store currency values accurately.
  • The __str__ method provides a human-readable representation of the model instance.

Using Models

Once you've defined your models, you can use Django's ORM (Object-Relational Mapping) to interact with the database.

Creating a Model Instance

book = Book(title="The Great Gatsby", author="F. Scott Fitzgerald", published_date="1925-04-10", price=10.99)
book.save()

Querying the Database

# Get all books
all_books = Book.objects.all()

# Get a book by title
book = Book.objects.get(title="The Great Gatsby")

# Filter books by author
fitzgerald_books = Book.objects.filter(author="F. Scott Fitzgerald")

Updating a Model Instance

book = Book.objects.get(title="The Great Gatsby")
book.price = 12.99
book.save()

Deleting a Model Instance

book = Book.objects.get(title="The Great Gatsby")
book.delete()

Migrating Models

After defining or modifying models, you need to create and apply migrations to update the database schema.

python manage.py makemigrations
python manage.py migrate

Integrating with Cloud Services

For deploying Django applications, you can use cloud services like Tencent Cloud. Tencent Cloud offers various services such as Cloud Virtual Machine (CVM) for hosting your application, Cloud Database (CDB) for your database needs, and more. This allows you to scale your application and manage your infrastructure efficiently.

By following these steps, you can effectively define and use models in Django to build robust and scalable web applications.