1、Django 中使用Model进行数据库的操作。
def index(request):
articles = Article.objects.all()
print(articles.query)
context = {}
context['articles'] = articles
return render(request, 'index.html', context)
其中第三行可以在命令行打印出相应的SQL语句。
通过articles = Article.objects.all()
操作来解释为SQL语句
在命令行中的打印结果是:
可以看出models把相应的查询解释为SQL语句。
SELECT
"zhidaily_article"."id", "zhidaily_article"."title", "zhidaily_article"."intro", "zhidaily_article"."abstract", "zhidaily_article"."category_id", "zhidaily_article"."content", "zhidaily_article"."publish_time", "zhidaily_article"."image", "zhidaily_article"."source_link", "zhidaily_article"."author_name", "zhidaily_article"."author_avatar", "zhidaily_article"."author_desc"
FROM
"zhidaily_article"
ORDER BY
"zhidaily_article"."publish_time"
DESC
其中FROM
指从哪个表提取数据,ORDER BY
指按哪组数据排序,这组数据只能是数字或者时间,DESC是排序方式。
2、Django中的搜索
def index(request):
q = request.GET.get('q', '')
articles = Article.objects.filter(title__contains=q)
print(articles.query)
context = {}
context['articles'] = articles
return render(request, 'index.html', context)
前端
<div class="item">
<form class="ui icon input">
<input type="text" name="q" placeholder="搜索指定用户文章">
<i class="search icon"></i>
</form>
</div>