一、Django ORM(对象关系映射)进行数据库查询操作
示例模型:
from django.db import models
from datetime import datetime, timedelta
class FruitModel(models.Model):
create_time = models.DateTimeField(auto_now_add=datetime.now())
update_time = models.DateTimeField(auto_now_add=datetime.now())
name = models.CharField(max_length=10)
price = models.IntegerField()
color = models.CharField(max_length=10)
class Meta:
db_table = "fruit_model"
1、查询所有对象
from myapp.models import FruitModel
# 获取模型中所有的对象
all_objects = FruitModel.object.all()
2、条件查询
from myapp.models import FruitModel
# 获取满足name是apple的对象
filter_objects = FruitModel.objects.filter(name="apple")
# 获取不满足name是apple的对象
excluded_objects = FruitModel.objects.exclude(name="apple")
3、获取单个对象
from myapp.models import FruitModel
# 根据主键获取单个对象
single_object_by_id = FruitModel.objects.get(id=1)
# 根据其他字段获取单个对象
single_object_by_field = FruitModel.objects.get(name="apple")
4、排序查询
from myapp.models import FruitModel
# 按照字段升序排序
ordered_objects = FruitModel.objects.order_by("create_time")
# 按照字段降序排序
reversed_ordered_objects = FruitModel.objects.order_by("-create_time")
5、其他查询
from django.db.models import Q, F
from myapp.models import FruitModel
1、使用Q对象进行复杂的查询逻辑
# 查询名为 “apple” 或者颜色为 “red” 的水果
fruits_queryset = FruitModel.filter(Q(name="apple") | Q(color="red"))
2、使用F对象进行字段之间的比较
# 查询名字和颜色相同的水果
same_name_and_color = FruitModel.objects.filter(name=F("color"))
二、比较运算符
from myapp.models import FruitModel
1、等于(=):FruitModel.objects.filter(name="apple")
2、不等于(!=):FruitModel.objects.exclude(name="apple")
3、大于(>):FruitModel.objects.filter(price__gt=20)
4、大于等于(>=):FruitModel.objects.filter(price__gte=20)
5、小于(<):FruitModel.objects.filter(price__lt=20)
6、小于等于(<=):FruitModel.objects.filter(price__lte=20)
7、指定范围内(in):FruitModel.objects.filter(price__in=[2021, 1, 30])
8、指定范围内(range):FruitModel.objects.filter(price__range=(1, 30))
9、包含指定值(contains):FruitModel.objects.filter(name__contains="apple")
10、包含指定值(icontains不区分大小写):FruitModel.objects.filter(name__icontains="apple")
11、以指定值开头(startswith):FruitModel.objects.filter(name__startswith="apple")
12、以指定值开头(istartswith不区分大小写):FruitModel.objects.filter(name__istartswith="apple")
13、以指定值结尾(endswith):FruitModel.objects.filter(name__endswith="apple")
14、以指定值结尾(iendswith不区分大小写):FruitModel.objects.filter(name__iendswith="apple")
标签:Django,name,models,数据库,查询,objects,import,FruitModel,apple
From: https://blog.csdn.net/xiongqianyuan/article/details/139165844