Home > front end >  How to reverse a filter class in Python/Django?
How to reverse a filter class in Python/Django?

Time:10-20

I needed to filter models instances with custom function, and using

Post.objects.filter(func)

didnt help, I got a type error cause "object is not iterable, so I went with

    def filter_posts(x):
        if x.author in followed_author_list:
            return True
        else:
            return False

posts = filter(filter_posts, Post.objects.all())
return render(request, 'main.html', {'posts':posts })

And it worked, but now I cant reverse the list, cause I want to order it so newest will be last. If I use list() on it, then posts stop appearing on my website at all, cause I assume its not a different type?..

Question is, how do I reverse filter class, or pull this off in general, so I get my posts filtered in reverse order?

CodePudding user response:

def users_by_active(active: bool):
    users = User.objects.all()
    ids = [user.id for user in users if user.is_active == active]
    return users.filter(id__in=ids)

you can make something similar to this function

best of luck

CodePudding user response:

So, I listened to your comments and started looking how to make query to the DB without loading all of it, to come up to conclusion objects.filter() I mentioned is the lazy method for queries, so my solution is

        followed_obj = Following.objects.filter(following_user=current_profile)
    followed_author_list = []
    for followed in followed_obj:
        followed_author_list.append(followed.profile.owner)
    posts = Post.objects.none()
    for author in followed_author_list:
        posts |= Post.objects.filter(author=author)
    posts = posts.order_by('date').reverse()

Thanks everyone for your input and helping me become a better developer :)

  • Related