# Django数据库操作记录

1 min read
Table of Contents

由于django的orm查询集不支持负切片,所以直接用负切片查询最后几条记录会出错

这里有2种解决思路

1.先将数据排序然后用正切片取前面的几条数据例如这样

new_data=Book_detail.objects.filter(book_id=book_id).order_by(‘-id’)[:5 ]

order_by()默认是升序排列,加上‘-’就是降序排列,我这里以id进行降序排列,取前5项,不同情况下选取不同的字段进行排序就行

2.使用原生sql语句

select * from book_book_info order by id desc limit 5;


💬 回复: Jun (2020-03-05)

# 查询以What开头的数据
Question.objects.filter(question_text__startswith='What')
# 查询今年发布的问卷(前提是pub_date是以 models.DateTimeField(“xx“)创建的)
Question.objects.get(pub_date__year=current_year)
# Django为主键查询提供了一个缩写:pk。下面的语句和Question.objects.get(id=1)效果一样
Question.objects.get(pk=1)

Comments