I am trying to build this nested for loop and my idea is that when I go to a URL like this: http://127.0.0.1:8000/posts/search?start=1&end=3
it will show me the posts within that range.
So far this is what I have:
def posts_search(request):
start = int(request.GET.get("start") or 0)
end = int(request.GET.get("end") or (start + 9))
posts = Post.objects.all()
data = []
for i in range(start, end + 1):
for post in posts:
x = post
data.append(x)
time.sleep(1)
return JsonResponse([post.serialize() for post in data
], safe=False)
The problem is when I go to that URL above, it is only outputting one post, the last post in the posts QuerySet. Regardless what start or end value I use in the URL. When I amend the for loop to this:
for i in range(start, end + 1):
for post in posts:
data.append(post)
The URL above outputs the whole posts QuerySey 3 times. Please could someone help me get this for loop right.
SOLVED:
start = int(request.GET.get('start') or 0)
end = int(request.GET.get('end') or start + 9)
posts = Post.objects.all()[start:end]
return JsonResponse(
{'data': [post.serialize() for post in posts]}
)