单个django queryset得到相邻的项目 [英] Single django queryset to get n adjacent items

查看:151
本文介绍了单个django queryset得到相邻的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个无限/连续滚动列表(如twitter),并希望能够导航到特定的项目。找到该项目是直截了当的,但是我需要在之前和之后收到一些项目。



我对这里提出的答案采用了类似的方法:在Django中获取下一个和上一个对象

  before = list(revers(models.MyModel.objects.filter(pk__lt = pk).order_by(' -  pk')[:10]))
after = list(models.MyModel.objects.filter(pk__gte = pk).order_by('pk')[:11])$ ​​b $ b objects = before + after
/ pre>

有没有办法将这些组合成一个查询?



我不能简单地组合两个与 | 运算符,如 before |之后而没有列表 / reverse ,因为片必须先到。我也不能像 pk__lt = pk + 10,pk__gt = pk-10 这样的东西,因为对象可能被删除。



对于一个更复杂的例子,如果我用除主键之外的东西订购,我需要先用另一个查询来获取对象:

  object = get_object_or_404(models.MyModel,pk = pk)
before = list(revers(models.MyModel.objects.filter(pk__lt = object.other_key).order_by(' - other_key ')[:10]))
after = list(models.MyModel.objects.filter(pk__gte = object.other_key).order_by('other_key')[:11])$ ​​b $ b objects = before +之后

同样,是否可以使用单个查询完成相同的事情?

解决方案

我曾经遇到过类似的问题,并以这里描述:定义描述对象的顺序的SQL变量,然后由t帽子。但是,这是纯SQL。我不知道有没有办法使用Django ORM。


I'm making an "infinite"/continuous scrolling list (like twitter) and want to be able to navigate to a specific item. Finding the item is straight forward, but I need to get a few items before and after it.

I'm using a similar approach to the answers suggested here: Getting next and previous objects in Django

before = list(reversed(models.MyModel.objects.filter(pk__lt=pk).order_by('-pk')[:10]))
after = list(models.MyModel.objects.filter(pk__gte=pk).order_by('pk')[:11])
objects = before + after

Is there any way to combine these into the one query?

I can't simply combine the two with the | operator, such as before | after and without list/reverse, as the slice must come first. I also can't do something like pk__lt=pk+10, pk__gt=pk-10 as objects may be deleted.

For a more complex example, if I was ordering by something other than the primary key I'd need to grab the object first with yet another query:

object = get_object_or_404(models.MyModel, pk=pk)
before = list(reversed(models.MyModel.objects.filter(pk__lt=object.other_key).order_by('-other_key')[:10]))
after = list(models.MyModel.objects.filter(pk__gte=object.other_key).order_by('other_key')[:11])
objects = before + after

Likewise, is it possible to accomplish the same thing with a single query?

解决方案

I once had a similar problem and solved it the way described here: defining an SQL-variable that describes the objects' order, and then ordering by that. However, that's plain SQL. I don't know if there's a way using the Django ORM.

这篇关于单个django queryset得到相邻的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆