Is there a way to restrict users to only see children of a parent element they belong to in Django Rest?

I have built a Django REST app for a client that allows users to join communities. The Community model has 20+ models that link back to it in some way (things like events, event dates, meetings, messages etc). I need a way to restrict users to only being able to perform CRUD operations on elements belonging to communities they are a part of. For example if user "John Smith" is a member of the "Animal Rescue Volunteers" community, he should only be able to read messages for that community and should not be able to create/edit messages in other communities.

I have seen people use the get_queryset method of a ViewSet to restrict RUD processes like so:

class MessageView(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer

    def get_queryset(self):
       return self.queryset.filter(message__community__in=self.request.user.communities)

However this doesn't solve the problem with Creates and needs to be applied to each ViewSet to work. Is there a better way to do this?

Back to Top