2

I have encountered one interesting problem

Lets say I have objects in my database likt this:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Lets consider numbers as ids of these objects

If I want to get two objects after 5, I need to use this query:

MyObject.objects.filter(id__gt=5).order_by("id")[:2]

This will return to me this result:

[6, 7]

Which is right result.

Now I want to get two objects before object 5. I do this query:

MyObject.objects.filter(id__lt=5).order_by("id")[:2]

However, this returns to me this:

[1, 2] instead of [3, 4]

So I need to query objects starting from object of id=5

I know that there is ranged query, but it does not suit when working only with ids.

Is it possible to query objects before certain id starting from this object itself?

======== UPDATE ========

There is a catch, sometimes objects are also filtered by another condition and this means that id's are not correlated by their indexes:

[34, 45, 46, 66, 100, 105, 211]

How it is possible to get two objects, for example, just before 66?

3
  • Did you use 2 underscores at id_lt? Or just 1 as in your example? Because I believe it's id__lt as far I've searched. Commented Mar 15, 2018 at 14:25
  • @KingReload it should be id__lt but still his order is ascending Commented Mar 15, 2018 at 14:33
  • @KingReload My bad. Just fixed it Commented Mar 15, 2018 at 14:40

2 Answers 2

3

By doing descending order

MyObject.objects.filter(id__lt=5).order_by("-id")[:2]

You will get 2 number nearest to 5


If you expect never to delete data then you can use range(between)

MyObject.objects.filter(id__range=(4, 3))
Sign up to request clarification or add additional context in comments.

Comments

2

we can get it by using slicing & descending ordering

 obj_id = 5
 MyObject.objects.filter(id__lt=obj_id).order_by("-id")[1:3]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.