在 django 标记中将有限的查询集传递给 related_to()

发布于 2024-12-17 10:34:12 字数 471 浏览 0 评论 0原文

我想在 django 标记中使用 lated_to() 函数,并且传递一个如下所示的查询集:

Chapter.objects.all().order_by('?')[:5]  #the important thing here is the "[:5]"

我的问题是该函数显然使用 in_bunk() 函数并且您Cannot use 'limit' or 'offset' with in_bulk

如何限制我的查询集仅传递 5 个对象并同时使用 in_bunk?

我知道 related_to() 允许您传递变量 num (这是它应该返回的对象的数量),但我不希望它每次都输出相同的查询集。因此,我想到了随机排序并在将其传递给函数之前对其进行限制的想法。但正如您所看到的:有限的查询集和bunk_it并不能很好地齐头并进。

I want to use the related_to() function in django-tagging and I am passing a queryset looking like this:

Chapter.objects.all().order_by('?')[:5]  #the important thing here is the "[:5]"

My problem is that this function apparently uses the in_bunk() function and you Cannot use 'limit' or 'offset' with in_bulk

How can I restrict my queryset to only pass 5 objects and at the same time make use of in_bunk?

I know that related_to() lets you pass the variable num (which is the number of objects it should return) but I don't want it to output the same queryset every single time. So i came up with the idea of ordering it randomly and limiting it before it was passed to the function. But as you can see: limited querysets and bunk_it doesn't go hand in hand very well.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

墨落画卷 2024-12-24 10:34:12

我找到了一个解决方案,尽管它不是最好的,并且它处理了不必要的数据。我只需运行与当前实例相关的模型的所有实例,然后随机排序并随后切片:

related_objects = instance.related_to(Model)        # all related objects are found
related_objects = random.sample(related_objects,5)  # .. and afterwards sorted randomly and sliced

I found a solution though it wasn't the best and though it processes unnecessary data. I simply run through all instances of the model related to the current instance and I then sort randomly and slice afterwards:

related_objects = instance.related_to(Model)        # all related objects are found
related_objects = random.sample(related_objects,5)  # .. and afterwards sorted randomly and sliced
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文