Django 的 Model Querying 提供了一系列方法,可以方便地对数据库进行查询。以下是一些常用的方法:
from myapp.models import MyModel
all_records = MyModel.objects.all()
from myapp.models import MyModel
filtered_records = MyModel.objects.filter(name="pidancode.com")
from myapp.models import MyModel
excluded_records = MyModel.objects.exclude(name="pidancode.com")
from myapp.models import MyModel
ordered_records = MyModel.objects.order_by("-age")
from myapp.models import MyModel
values_records = MyModel.objects.values("name", "age")
from myapp.models import MyModel
distinct_records = MyModel.objects.distinct("name")
代码演示:
假设我们有一个简单的模型,如下所示:
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField()
email = models.CharField(max_length=50)
def __str__(self):
return self.name
我们向 MyModel 中添加了一些数据:
MyModel.objects.create(name="pidancode.com", age=18, email="contact@pidancode.com")
MyModel.objects.create(name="皮蛋编程", age=22, email="pidan@pianochuan.com")
MyModel.objects.create(name="pidancode.com", age=20, email="info@pidancode.com")
现在,我们可以使用以上方法对数据库进行查询:
# 查询所有记录
all_records = MyModel.objects.all()
# 根据条件查询记录
filtered_records = MyModel.objects.filter(name="pidancode.com")
# 排除符合条件的记录
excluded_records = MyModel.objects.exclude(name="pidancode.com")
# 按照指定字段排序
ordered_records = MyModel.objects.order_by("-age")
# 只查询指定字段的值
values_records = MyModel.objects.values("name", "age")
# 去重查询
distinct_records = MyModel.objects.distinct("name")
以上方法会返回 QuerySet 对象,可以使用循环或索引进行访问。例如:
# 遍历 QuerySet
for record in filtered_records:
print(record.name, record.age, record.email)
# 访问 QuerySet 中的第一条记录
first_record = filtered_records[0]
print(first_record.name, first_record.age, first_record.email)