首页 > 解决方案 > 如何限制 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])但可惜的是,到目前为止还没有任何效果。我在这里做错了什么?我敢肯定这只是一个愚蠢的错误。

标签: pythondjango

解决方案


过滤的构造方式对限制结果的数量没有影响。您可以使用:

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应该是对的引用,而不是该类的对象。


推荐阅读