Detailed explanation of Django ORM, the ORM framework in Python

王林
Release: 2023-06-11 09:12:07
Original
2706 people have browsed it

Django ORM is a classic ORM framework in Python. It is part of the Django Web framework and provides a convenient way for database operations. ORM stands for Object Relational Mapping, which can map tables in relational databases to classes in Python, thereby simplifying the development process and improving development efficiency. This article will introduce Django ORM in detail.

I. The basic concept of ORM

ORM is a technology that maps objects to relational databases. It mainly implements the following three functions:

  • Tables in the database are mapped to classes in Python
  • Fields in the database are mapped to attributes in Python
  • Records in the database are mapped to instances in Python

The main advantage of ORM is that it can reduce the time and workload of developers writing repeated SQL statements, and it can reduce errors caused by adjustments and changes to SQL statements.

II. Advantages of Django ORM

Compared with other ORM frameworks, Django ORM has the following advantages:

  • Simple and easy to use: Django ORM’s API is very simple , easy to master and use.
  • Rich API: Django ORM provides a rich API to complete common database operations, such as addition, deletion, modification, query, etc. It also supports operations such as advanced query and aggregation query.
  • Has good scalability: Django ORM can be seamlessly integrated with other third-party libraries, such as Django REST framework, Django-Oscar, etc.
  • Automatic mapping: Django ORM supports automatic mapping. Developers only need to define the structure of the database table, and the corresponding Python class can be automatically generated, thereby reducing the amount of repeated code during the development process.

III. How to use Django ORM

  1. Install Django

First you need to install Django, you can use pip to install:

pip install Django
Copy after login
  1. Define the model

When using Django ORM, you need to define the model class first. The model class is a class in Python that defines the fields in the data table and other parts of the data table. Metadata, such as table names, indexes, etc. The following is a simple model class definition:

from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) pub_date = models.DateTimeField()
Copy after login

In the above code, we use themodelsmodule provided by Django ORM to define a class namedBookData table, which contains three fields:title,author,pub_date.max_lengthis used to specify the maximum length of string type fields,DateTimeFieldis used to store time type fields.

  1. Create database table

After completing the definition of the model class, you need to generate the database table through migration. Django ORM provides an automatic migration function. You only need to run the following command to generate a data table:

python manage.py makemigrations python manage.py migrate
Copy after login

The above command creates theBooktable, and the table structure corresponds to the defined model class.

  1. CRUD operation

a. Create records

You can easily add new records to the data table through the model class. In the following code, We create a new record and save it to the database:

from datetime import datetime book = Book(title='Django ORM Tutorial', author='Terry', pub_date=datetime.now()) book.save()
Copy after login

b. Updating the record

Updating a record using Django ORM is very simple, just query the record first and then update it and save it. The following is a simple update code example:

book = Book.objects.get(id=1) book.title = 'Updated Title' book.save()
Copy after login

c. Delete records

Deleting records is also very simple, just execute the following code:

book = Book.objects.get(id=1) book.delete()
Copy after login

d. Query Record

In Django ORM, you can useobjectsobjects to query. The following is a simple query example code:

books = Book.objects.all() for book in books: print(book.title, book.author, book.pub_date)
Copy after login

This code will outputBookThetitle,author, andpub_datefields for all records in the table.

IV. Advanced query operations

In addition to basic CRUD operations, Django ORM also supports some advanced query operations, such as join table query, query condition combination, aggregation operation, etc. The following are some examples code.

a. Join table query

Django ORM supports two methods of join table query: one is to associate through theForeignKeyfield, and the other is to associate through the self- Define queries to perform correlations.

# 通过ForeignKey字段关联 class Author(models.Model): name = models.CharField(max_length=50) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) books = Book.objects.filter(author__name='Leo Tolstoy') # 以上代码查询了作者名为'Leo Tolstoy'的所有图书 # 通过自定义查询进行关联 books = Book.objects.raw('SELECT * FROM app_book INNER JOIN app_author ON app_book.author_id = app_author.id WHERE app_author.name = %s', ['Leo Tolstoy'])
Copy after login

b. Query condition combination

In Django ORM, you can use theQobject to combine multiple query conditions to achieve more complex queries. The following is a sample code:

from django.db.models import Q books = Book.objects.filter(Q(title__contains='Django') | Q(author__contains='Guido')) # 以上代码查询了标题中包含'Django'或作者名中包含'Guido'的所有图书
Copy after login

c. Aggregation operation

Aggregation operation is used to group data or summarize statistics. Aggregation operations supported in Django ORM include:Avg,Max,Min,Count,Sum, etc. The following is a sample code:

from django.db.models import Avg avg_pub_date = Book.objects.all().aggregate(Avg('pub_date')) # 以上代码计算了所有图书的发布时间的平均值
Copy after login

V. Summary

This article provides a detailed introduction to the ORM framework Django ORM in Python. Django ORM is an easy-to-use, feature-rich, and scalable ORM framework that can help developers achieve rapid development and more efficient database operations. In addition to basic CRUD operations, Django ORM also supports some advanced query operations, such as join table queries, query condition combinations, aggregation operations, etc., which can meet the needs of more data operations.

The above is the detailed content of Detailed explanation of Django ORM, the ORM framework in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!