0

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Hobhouse
  • 15,463
  • 12
  • 35
  • 43

1 Answers1

3

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.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895