[Answer]-Django – negative query in one-to-many relationship

1👍

What you need is this:

comments_by_others_in_profile_posts = Comment.objects \
    .filter(blog__created_by=profile) \
    .exclude(created_by=profile)

profile.posts.exclude(comments=comments_by_others_in_profile_posts)

You can also try it like this (i believe this way it can be a little bit faster, but need to see the queries EXPLAIN output):

profile.posts.exclude(id__in=comments_by_others_in_profile_posts.values_list('blog', flat=True))
👤Todor

0👍

Well you were almost there, just need to include the conditions from your instincts. A good way to go about this is to use the django shell and a bunch of test data that matches your permutations. For more complex queries, its a good idea to write a unit test first.

profile.posts.filter(Q(comments__isnull=True)|~Q(comments__created_by=profile, comments__created_by__isnull=False))

Leave a comment