SoFunction
Updated on 2025-04-14

How to use Django for details

Preface

In Django,modelsIt is the core tool for processing databases, allowing us to describe data structures by defining Python classes and automatically generate database tables. This article will explain how to use Django's model to design and manipulate database tables.

1. What is the Django model?

The Django model is a Python class, inherited fromClass, each model class corresponds to a table in the database. The properties of the model class define the fields (columns) of the table and can operate on the data in the table through various methods (such as adding, deleting, modifying, and querying).

2. Create a Django model

Suppose we are developing a simple application that manages the basic information of the tank. We can define aTankThe model stores the tank's name, health and speed attributes.

2.1 Defining a model

In Django, you usually applyDefine the model class in the file. Each field is oneFieldType, Django will automatically create corresponding columns of the database table for each field.

# 

from  import models

class Tank():
    name = (max_length=100)  # The name of the tank    health = ()           # Tank's health    speed = ()              # Tank speed    created_at = (auto_now_add=True)  # Create time
    def __str__(self):
        return 

2.2 Field Type

In the model, we define different types of fields:

  • CharField(max_length=100): used to store string data,max_lengthParameters specify the maximum length of the field.
  • IntegerField(): Used to store integer values.
  • FloatField(): Used to store floating decimal points.
  • DateTimeField(auto_now_add=True): used to store date and time,auto_now_add=TrueIndicates that the current time is automatically set every time an object is created.

2.3 String representation (__str__

We rewritten__str__Method, ensure that the name of the tank is returned in the management interface or when passing the query.

3. Create a database table

After defining the model, Django will generate a database table based on the model. Next, we need to synchronize the model to the database through the migration operation.

3.1 Generate migration files

Use the following command to generate the migration file, and Django will automatically generate database operation scripts based on the changes in the model:

python  makemigrations

3.2 Application migration

Perform a migration operation to synchronize the model to the database:

python  migrate

4. Use the model to perform data operations

Django provides a powerful ORM (object relational mapping) system. Through the model class, you can easily add, delete, modify, and check operations.

4.1 Create an object and save it

You can use the model class to create new data records and save them to the database:

tank = Tank(name="T-34", health=100, speed=50.0)
()  # Save the object to the database

4.2 Query data

You can use the modelobjectsProperties execute database query. Django provides a variety of query methods, common ones include:

  • all(): Get all records.
  • get(): Get a single record based on the conditions.
  • filter(): Filter records according to conditions.
  • exclude(): Exclude certain records.
# Get all tankstanks = ()

# Get a tank with id 1tank = (id=1)

# Get tanks with speeds greater than 40fast_tanks = (speed__gt=40)

# Exclude tanks with health less than 50healthy_tanks = (health__lt=50)

4.3 Update Objects

The query object is modifiable, you can directly modify its properties and save:

tank = (id=1)
 = 60.0  # Modify speed()  # Save and modify

4.4 Delete Objects

You can delete records in the database:

tank = (id=1)
()  # Delete the tank object

5. Common field types and parameters

Django provides a rich variety of field types for processing a variety of different types of data. Common field types and parameters are as follows:

5.1 CharField

Used to store strings, usually used to store short text such as names and titles.

name = (max_length=100)
  • max_length: Maximum length of the field (required).

5.2 IntegerField

Used to store integers.

health = ()
  • null: IfTrue, this field can be empty.
  • blank: IfTrue, this field can be empty in the form.

5.3 DateTimeField

Used to store dates and times.

created_at = (auto_now_add=True)
  • auto_now: Automatically set to the current time each time the model is saved.
  • auto_now_add: Automatically set to the current time only when the object is created.

5.4 ForeignKey

Represents a one-to-many relationship. Usually used to associate other models.

author = ('Author', on_delete=)
  • on_delete: Defines the behavior when deleting associated objects. Common options are:
    • : Cascading deletion, and the current object is also deleted when deleting the associated object.
    • models.SET_NULL: Set the foreign key field toNULL
    • : Prevents deletion of associated objects.
    • models.SET_DEFAULT: Set the foreign key field to the default value.

5.5 ManyToManyField

Represents a many-to-many relationship. Applicable to relationships between multiple model instances and multiple other model instances.

authors = ('Author')
  • related_name: Defines the name of the reverse relationship.

5.6 BooleanField

Used to store boolean values ​​(TrueorFalse)。

is_active = (default=True)
  • default: Set the default value of the field.

6. Migrate and manage using models

6.1 Management backend

Django provides a built-in management backend to facilitate you to manage model data. You just need toRegister your model in  .

# 

from  import admin
from .models import Tank

(Tank)

6.2 Custom model management

You can also customize the management methods of the model to simplify common queries or operations. For example, you can add some common query methods by customizing management classes:

class TankManager():
    def fast_tanks(self):
        return (speed__gt=50)

class Tank():
    name = (max_length=100)
    speed = ()

    objects = TankManager()  # Use custom management classes

In this way, you can pass.fast_tanks()To obtain all tanks with speeds greater than 50.

7. Summary

Django's model is a bridge to interact with the database. By defining model classes, you can easily add, delete, modify, and check operations without directly writing SQL statements. By rationally using model fields, foreign keys, many-to-many relationships and other functions, you can build complex database structures and manage data efficiently.

In actual applications, you can also extend the functionality of the model through custom methods, query sets, managers, etc., making Django's ORM more flexible and powerful.

This is the end of this article about how to use Django. For more information about using Django, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!