Django 的 ORM(对象关系映射)提供了一种方便的方式来与数据库进行交互。
在 `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
运行迁移命令来创建数据库表:
python manage.py makemigrations python manage.py migrate
from myapp.models import Person # 创建并保存一个新对象 person = Person(name='Alice', age=25, city='New York') person.save()
create()
方法person = Person.objects.create(name='Bob', age=30, city='Los Angeles')
people = Person.objects.all() for person in people: print(person.name, person.age, person.city)
person = Person.objects.get(id=1) print(person.name, person.age, person.city)
# 获取所有年龄大于25的人 people = Person.objects.filter(age__gt=25) for person in people: print(person.name, person.age, person.city)
person = Person.objects.get(id=1) person.age = 26 person.save()
Person.objects.filter(city='New York').update(city='NYC')
person = Person.objects.get(id=1) person.delete()
Person.objects.filter(age__lt=20).delete()
people = Person.objects.all().order_by('age') for person in people: print(person.name, person.age, person.city)
people = Person.objects.all().order_by('city', '-age') for person in people: print(person.name, person.age, person.city)
Django ORM 不直接支持分组操作,但可以使用 annotate
和 aggregate
方法来实现类似的功能。
annotate
进行分组计数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'])
aggregate
进行聚合操作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}
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)
from django.db.models import F # 获取年龄大于等于城市长度的人 people = Person.objects.filter(age__gte=F('city__length')) for person in people: print(person.name)
上一篇:centos清空history
下一篇:初识Spring Web MVC