Search code examples
pythonjsondjangodjango-viewsfor-in-loop

How to avoid using a return statement in a for-in loop?


My view below is only going through one iteration cycle and then breaking out the loop. I know that it's probably because of the return statement in this line: return JsonResponse([post.serialize() for post in posts], safe=False) but how can I avoid this?

I tried changing the return statement to a print statement instead but then I get a ValueError: The view network.views.followingPosts didn't return an HttpResponse object. It returned None instead.

Just before the except statement I tried putting a continue there but this had no effect.

I'm not really sure how to fix this. Any ideas?

def followingPosts(request, user_username):
    try:
        user_profile = get_object_or_404(User, username=user_username)
        following_users = user_profile.get_following()
        for person in following_users:
            posts = Post.objects.filter(creator=person)
    except Profile.DoesNotExist:
        return JsonResponse({"error": "No user found."}, status=404)

    if request.method == "GET":
        return JsonResponse([post.serialize() for post in posts], safe=False)
    
    else:
        return JsonResponse({
            "error": "GET request required."
        }, status=400)

Solution

  • As @quamrana, I think that the loop is implemented well, except that you store posts only for the last loop run. Here is the correction:

    def followingPosts(request, user_username):
        try:
            user_profile = get_object_or_404(User, username=user_username)
            following_users = user_profile.get_following()
            posts = list()
            for person in following_users:
                posts += Post.objects.filter(creator=person)
        except Profile.DoesNotExist:
            return JsonResponse({"error": "No user found."}, status=404)
    
        if request.method == "GET":
            return JsonResponse([post.serialize() for post in posts], safe=False)
        
        else:
            return JsonResponse({
                "error": "GET request required."
            }, status=400)
    

    Also, it is a good habit to keep a single line in the try-clause. Therefore, what about

    def followingPosts(request, user_username):
        try:
            user_profile = get_object_or_404(User, username=user_username)
        except Profile.DoesNotExist:
            return JsonResponse({"error": "No user found."}, status=404)
    
        if request.method == "GET":
            following_users = user_profile.get_following()
            posts = list()
            for person in following_users:
                posts += Post.objects.filter(creator=person)
            return JsonResponse([post.serialize() for post in posts], safe=False)
        
        else:
            return JsonResponse({
                "error": "GET request required."
            }, status=400)