66.ORM查询条件:startswith和endswith的使用 您所在的位置:网站首页 Python中startwith用法 66.ORM查询条件:startswith和endswith的使用

66.ORM查询条件:startswith和endswith的使用

2023-09-16 04:50| 来源: 网络整理| 查看: 265

定义模型的models.py,示例代码如下: from django.db import models class Category(models.Model): name = models.CharField(max_length=100) class Meta: db_table = 'category' class Article(models.Model): title = models.CharField(max_length=100) content = models.TextField() category = models.ForeignKey('Category', on_delete=models.CASCADE, null=True) def __str__(self): return "" % (self.id, self.title, self.content) class Meta: db_table = 'article' 1. startswith:大小写敏感的判断某个字段的值是否以某个值开始的。示例代码如下: from .models import Article, Category from django.http import HttpResponse def index(request): articles = Article.objects.filter(title__startswith='hello') print(articles) print(articles.query) return HttpResponse("success") 首先,查看数据库表中的数据如下:

在这里插入图片描述

打印出结果:

:返回的QuerySet为空。 SELECT article.id, article.title, article.content, article.category_id FROM article WHERE article.title LIKE BINARY hello%. 需要注意的是这里执行的sql语句为LIKE BINARY hello%,LIKE BINARY代表的是区分大小写,hello%代表的是以hello为开头,%代表的是后面可以匹配任意多个字符。

2.istartswith: 大小写不敏感的判断某个字段的值是否以某个值开始的,示例代码如下: from .models import Article, Category from django.http import HttpResponse def index(request): articles = Article.objects.filter(title__istartswith='hello') print(articles) print(articles.query) return HttpResponse("success") 打印出结果如下:

: 查找出两条符合条件的文章。 SELECT article.id, article.title, article.content, article.category_id FROM article WHERE article.title **LIKE hello%: 需要注意的是,这里将查询条件翻译成了sql语句为:article.title LIKE hello%,这里的LIKE代表的是不区分大小写,hello%代表的是以hello开头,后面可以匹配任意多个字符。

3.endswith: 大小写敏感的判断某个字段的值中是否含有某个值开始。示例代码如下: from .models import Article, Category from django.http import HttpResponse def index(request): articles = Article.objects.filter(title__endswith='world') print(articles) print(articles.query) return HttpResponse("success") 打印出结果如下:

输出的结果为空的QuerySet。 SELECT article.id, article.title, article.content, article.category_id FROM article WHERE article.title LIKE BINARY %world :这里的查询条件被翻译article.title LIKE BINARY %world,LIKE BINARY代表的是区分大小写的判断,%world代表的是以world为结束,前面可以匹配任意多个字符,如果可以满足条件就会返回。

4.iendswith: 不区分大小写判断某个字段的值中是否含有某个值,示例代码如下: from .models import Article, Category from django.http import HttpResponse def index(request): articles = Article.objects.filter(title__iendswith='world') print(articles) print(articles.query) return HttpResponse("success") 打印出结果如下所示:

: 返回了一个满足条件的文章 SELECT article.id, article.title, article.content, article.category_id FROM article WHERE article.title LIKE %world: 需要注意的是,这里为 LIKE,代表的是不区分大小写的判断,并且以world结尾,world前面可以匹配任意多个字符,满足条件才会被返回。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有