Technology Sharing

Django's common ORM operations such as adding, deleting, modifying, checking, sorting, grouping, etc.

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Django's ORM (object-relational mapping) provides a convenient way to interact with the database.

1. Django Model


在 `myapp/models.py` 中定义一个示例模型:

```python
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    city = models.CharField(max_length=100)

    def __str__(self):
        return self.name
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

Run the migration command to create the database tables:

python manage.py makemigrations
python manage.py migrate
  • 1
  • 2

2. Create

Creating a Single Object
from myapp.models import Person

# 创建并保存一个新对象
person = Person(name='Alice', age=25, city='New York')
person.save()
  • 1
  • 2
  • 3
  • 4
  • 5
use create() method
person = Person.objects.create(name='Bob', age=30, city='Los Angeles')
  • 1

3. Read

Get all objects
people = Person.objects.all()
for person in people:
    print(person.name, person.age, person.city)
  • 1
  • 2
  • 3
Get a single object
person = Person.objects.get(id=1)
print(person.name, person.age, person.city)
  • 1
  • 2
Use filters
# 获取所有年龄大于25的人
people = Person.objects.filter(age__gt=25)
for person in people:
    print(person.name, person.age, person.city)
  • 1
  • 2
  • 3
  • 4

4. Update

Updating a Single Object
person = Person.objects.get(id=1)
person.age = 26
person.save()
  • 1
  • 2
  • 3
Batch Update
Person.objects.filter(city='New York').update(city='NYC')
  • 1

5. Delete

Deleting a single object
person = Person.objects.get(id=1)
person.delete()
  • 1
  • 2
batch deletion
Person.objects.filter(age__lt=20).delete()
  • 1

6. Ordering

Sort by a single field
people = Person.objects.all().order_by('age')
for person in people:
    print(person.name, person.age, person.city)
  • 1
  • 2
  • 3
Sort by multiple fields
people = Person.objects.all().order_by('city', '-age')
for person in people:
    print(person.name, person.age, person.city)
  • 1
  • 2
  • 3

7. Grouping

Django ORM does not directly support grouping operations, but you can use annotate andaggregate method to achieve similar functionality.

use annotate Perform group counting
from django.db.models import Count

# 按城市分组并计数
city_counts = Person.objects.values('city').annotate(count=Count('id'))
for city_count in city_counts:
    print(city_count['city'], city_count['count'])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
use aggregate Perform aggregation operations
from django.db.models import Avg, Max, Min

# 计算平均年龄
average_age = Person.objects.aggregate(Avg('age'))
print(average_age)  # 输出: {'age__avg': 27.5}

# 计算最大和最小年龄
age_stats = Person.objects.aggregate(Max('age'), Min('age'))
print(age_stats)  # 输出: {'age__max': 30, 'age__min': 25}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

8. Complex Queries

Q objects for complex queries
from django.db.models import Q

# 获取年龄大于25或城市为'New York'的人
people = Person.objects.filter(Q(age__gt=25) | Q(city='New York'))
for person in people:
    print(person.name, person.age, person.city)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
F objects perform field comparisons
from django.db.models import F

# 获取年龄大于等于城市长度的人
people = Person.objects.filter(age__gte=F('city__length'))
for person in people:
    print(person.name)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6