0

I'm having problems with filtering the query set. Here is a simplified data model:

Entry
- id
- broadcast_groups

User
- id
- groups

So an entry can be broadcasted (shared) in a group. I have a GET /entries/ endpoint that returns entry objects.

I want to filter a query set to return entries that fulfill following requirements:

  • are not broadcasted in any group OR
  • are broadcasted in groups the user is member of.

I'm scratching my head how to achieve this. I figured that maybe writing a custom FilterBackend is a good idea. Here is what I have so far:

class CanViewPublicOrGroupMemberEntriesFilterBackend(filters.BaseFilterBackend):

    def filter_queryset(self, request, queryset, view):
        user = request.user
        return queryset.filter(broadcast_groups__in=user.groups.all())

However, this does not yield results that I am expecting. What would be a filter() syntax to achieve such filtering? Or maybe I'm approaching the problem from the wrong side?

1 Answer 1

2

You are looking for Q objects https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q-objects

class CanViewPublicOrGroupMemberEntriesFilterBackend(filters.BaseFilterBackend):
    def filter_queryset(self, request, queryset, view):
        user = request.user
        return queryset.filter(
            Q(broadcast_groups__in=user.groups.all()) |
            Q(broadcast_groups__isnull=True)
        )
Sign up to request clarification or add additional context in comments.

1 Comment

This is so simple!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.