Search code examples
djangodjango-mptt

How do I build a queryset in django retrieving threads in which a user has posted?


I'm making a threaded forum app using django-mptt. Everything is up and running, but I have trouble building one specific queryset.

I want to retrieve posts which:

  1. are root nodes
  2. are posted by current_user or have a descendant posted by current_user.

What I have so far is this:

Post.objects.filter(Q(user = current_user) | Q(  )).exclude(parent__gt = 0)

in my second Q I need something to tell whether the current_user has posted one of its descendants. Anyone know if it's even possible?


Solution

  • I don't think you can do this in one query. Here's how to do it in two:

    thread_ids = Post.objects.filter(user=current_user).values_list('tree_id', flat=True)
    posts = Post.objects.filter(tree_id__in=thread_ids, level=0)
    

    This gets the MPTT tree id of every thread which the user has posted in. Then it gets the root node of each of these threads.