python - 如何限制 django lamba 查询中的响应大小
问题描述
我知道在 Django 中限制查询的典型方法是将 [:10] 附加到查询的末尾,但我有一个使用 a 的函数,functools.reduce(lambda
我不确定如何限制查询大小。就目前而言,查询花费的时间太长并且获取的数据太多。限制此查询并提高效率的最佳方法是什么?
这是功能:
def get_threads_for_student_mentor(cls, student_id=None, mentor_id=None):
clauses = []
if student_id:
clauses.append(models.Q(student_id=student_id))
if mentor_id:
clauses.append(models.Q(mentor_id=mentor_id))
if len(clauses) == 0:
raise ValueError("student_id and mentor_id cannot both be None")
return cls.objects.filter(functools.reduce(lambda a, b: a & b, clauses))
我尝试将 return 语句更改为,return cls.objects.filter(functools.reduce(lambda a, b: a & b, clauses))[:5].all()
并尝试将其添加到 append 函数中,
clauses.append(models.Q(student_id=student_id)[:5])
但可惜的是,到目前为止还没有任何效果。我在这里做错了什么?我敢肯定这只是一个愚蠢的错误。
解决方案
过滤的构造方式对限制结果的数量没有影响。您可以使用:
return cls.objects.filter(functools.reduce(lambda a, b: a & b, clauses))[:5]
您还可以使用以下方法简化过滤:
def get_threads_for_student_mentor(cls, student_id=None, mentor_id=None):
clauses = {}
if student_id:
clauses['student_id'] = student_id
if mentor_id:
clauses['mentor_id'] = mentor_id
if not clauses:
raise ValueError('student_id and mentor_id cannot both be None')
return cls.objects.filter(**clauses)[:5]
cls
应该是对类的引用,而不是该类的对象。
推荐阅读
- c# - 使用匿名操作调用 ForEach
- android-studio - (Android Studio)在我的 GridView 中单击某些位置在非常特殊的情况下不起作用
- vba - 将单词表单元格中的值设置为范围
- c# - 对话框以错误的路径打开文件夹
- ruby-on-rails - 优化 Elastic Beanstalk Ruby on Rails 的成本
- python - 当传递一个包含嵌入空格的字符串的元组时,为什么easygui会插入大括号?
- algorithm - 递归函数的空间复杂度分析
- google-apps-script - iterate through selected cells in Google Sheets
- android - 我没有从谷歌获得任何适合安卓应用的用户数据
- core-plot - CorePlot:将 Y 轴更改为从 3 开始,而不是 0