How do I build a queryset in django retrieving threads in wich a user has posted?
-
05-07-2019 - |
Question
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 wether 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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow