python - Django 中的切片与查询集

标签 python django django-queryset

这一切都始于我尝试将切片应用于查询集以限制它。据我了解 documentation它应该将结果限制为 10 个条目:

def get_queryset(self, *args, **kwargs):

    qs = Message.objects.all()  
    qs = qs.filter(Target_id=self.dialog)[:10]    # here the limit
    qs = qs.annotate(sender_id=Max('Sender__id')) 
    return qs

但实际上在模板中,请求返回了我所有的记录,但只将注释应用于前 10 个。我不知道为什么。

我以为整个原因是注释。

然后我删除最后一行(带注释)。但是我在模板中得到了所有记录而不是 10 条记录。这与我没有制作切片的结果相同。

在我的模板中,我没有做任何不寻常的事情:对我的查询集的迭代:

{% for message in messages %}
  {{message}}
{% endfor %}

这很奇怪:如果我在 View 中使用 len(qs),我会得到 10!但在模板中我得到 300!它不适合我的头脑。

我也尝试在模板中应用 slice 而不是我的 View :

{% for message in messages|slice:":10" %}

但一切都没有改变。

我的模板中有所有消息,而不是 10 条。这怎么可能?

PS:数据库类型是sqlite。

最佳答案

documented that it is not advisable to futher modify a queryset after slicing :

Also note that even though slicing an unevaluated QuerySet returns another unevaluated QuerySet, modifying it further (e.g., adding more filters, or modifying ordering) is not allowed, since that does not translate well into SQL and it would not have a clear meaning either.

您应该更改顺序,例如:

def get_queryset(self, *args, **kwargs):
    return Message.objects.filter(Target_id=self.dialog).annotate(
        sender_id=Max('Sender__id')
    )[:10]

所以你首先 .filter(..)/.annotate(..),然后切片。

关于python - Django 中的切片与查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57136129/

相关文章:

python - 从python中的for循环返回值

python sys.stdin.read() 不需要的拆分

python - Django一对一反向关系DoesNotExist

python - 使用线程时 Django 中的数据库错误

django - 使用 Django 中的多个字段进行计数(不同)

django - 关系 (x > 1)-对多

python - 如何在将图像提供给 CoreML 模型之前对其进行预处理?

python - 如何使用带有 OpenCV 的 Harris 检测器正确检测角点?

django - 为通用 get_context_data 扩展通用 View 类

django - 在 Django 模型查询集上切片