-1

as part of learning django, I am creating a blog website and also a user follow model. Here in the homepage I am able to see only the posts from the people I follow and not the users own posts. I tried using chained filter/ multiple filter but it seems it doesn't work in this case. Please have a look at this view code and let me know what changes I should make here.

    @login_required
def myhome(request, tag_slug=None):
    current_user = request.user
    following_ids = request.user.following.values_list('id',flat=True) 
    actions = Action.objects.filter(user_id__in=following_ids) #Action notification
    posts_list = Post.objects.filter(user_id__in=following_ids).filter(user=current_user).\
                                order_by('-post_date') #See only followed people post
    tag = None
    if tag_slug:
        tag = get_object_or_404(Tag, slug=tag_slug)
        posts_list = posts_list.filter(tags__in=[tag])

    paginator = Paginator(posts_list, 5)
    page = request.GET.get('page')
    try:
        posts = paginator.page(page)
    except PageNotAnInteger:
        posts = paginator.page(1)
    except EmptyPage:
        posts = paginator.page(paginator.num_pages)
    if following_ids:
        actions = actions.filter(user_id__in=following_ids)
        actions = actions.select_related('user', 'user__profile').prefetch_related('target')[:10]

    context = {
            'page':page,
            'posts':posts,
            'tag':tag,
            'actions':actions,
    }
    return render(request, 'posts/users/myhome.html', context)

Thanks in advance!

Danny
  • 287
  • 7
  • 30

1 Answers1

2

If I understand you correctly you are trying to get all the posts of the user plus the posts of the users that the user follows. If that is the case I don't think you will be able to do it by chaining filters, because you want an "OR" condition.

So, you can achieve this in several ways, one simple way is to use | operator, like this,

posts_list = Post.objects.filter(user_id__in=following_ids) | Post.objects.filter(user=current_user)

But I think Django construction for this and other complex cases are Q objects. Something like this should work,

from django.db.models import Q

posts_list = Post.objects.filter(Q(user_id__in=following_ids) | Q(user=current_user))

Here you have a nice discussion of this subject (How do I do an OR filter in a Django query?)[How do I do an OR filter in a Django query?.

cabesuon
  • 4,860
  • 2
  • 15
  • 24