标签:题目 默认 image asc django 判断 max col -o
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)
create_time = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return "<(Article: id: %s,title: %s, content: %s)>" % (self.id, self.title, self.content)
class Meta:
db_table = 'article'
from django.http import HttpResponse
from .models import Article
def index2(request):
# 1.isnull: 查找创建时间create_time是空的文章
articles = Article.objects.filter(create_time__isnull=True)
print(articles)
print(articles.query)
# 2. isnull: 同样,也可以查找create_time非空的文章
article = Article.objects.filter(create_time__isnull=False)
print(article)
print(article.query)
return HttpResponse('success!')
def index2(request):
# 3.regex大小写敏感的正则表达式,
# 判断以hello开头的字符串
articles = Article.objects.filter(title__regex=r'^hello')
print(articles)
print(articles.query)
# 4.iregex大小写敏感的正则表达式
# 判断以hello开头的字符串
articles = Article.objects.filter(title__iregex=r'^hello')
print(articles)
print(articles.query)
return HttpResponse('success!')
<QuerySet []>,返回的QuerySet为空。
SELECT article
.id
, article
.title
, article
.content
, article
.category_id
, article
.create_time
FROM article
WHERE article
.title
REGEXP BINARY ^hello,需要注意的是,这里django底层执行的sql语句为BINARY 即代表的是区分大小写进行判断。
<QuerySet [<Article: <(Article: id: 1,title: Hello, content: 你好)>>, <Article: <(Article: id: 2,title: Hello World, content: 大家好)>>]>,返回两条满足正则表达式的数据。
SELECT article
.id
, article
.title
, article
.content
, article
.category_id
, article
.create_time
FROM article
WHERE article
.title
REGEXP ^hello,这里执行的sql语句为正则表达式匹配^hello,并不区分大小写。
def index3(request):
# 查找文章题目中包含中国的文章分类
# 注意:contains区分大小写判断某字段中的值是否包含某个值
# 在被翻译成了sql语句的时候会被翻译成LIKE BINARY.
category = Category.objects.filter(article__title__contains='中国')
print(category)
print(category.query)
return HttpResponse("success!")
<QuerySet [<Category: Category object (3)>]>
SELECT category
.id
, category
.name
FROM category
INNER JOIN article
ON (category
.id
= article
.category_id
) WHERE article
.title
LIKE BINARY %中国%
标签:题目 默认 image asc django 判断 max col -o
原文地址:https://www.cnblogs.com/guyan-2020/p/12264539.html