python - Single django queryset to get n adjacent items -
i'm making "infinite"/continuous scrolling list (like twitter) , want able navigate specific item. finding item straight forward, need few items before , after it.
i'm using similar approach answers suggested here: getting next , 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 way combine these 1 query?
i can't combine 2 |
operator, such before | after
, without list
/reverse
, slice must come first. can't pk__lt=pk+10, pk__gt=pk-10
objects may deleted.
for more complex example, if ordering other primary key i'd need grab object first yet 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, possible accomplish same thing single query?
i once had similar problem , solved way described here: defining sql-variable describes objects' order, , ordering that. however, that's plain sql. don't know if there's way using django orm.
Comments
Post a Comment