I have three models where one Document has many Blocks and one Block has many Comments.
class Document(models.Model):
name = models.Charfield()
class Block(models.Model):
document = models.ForeignKey(to=Document)
class Comment
block = models.ForgeinKey(to=Block)
Users can have permissions for Document
which allows them to see all Block
s in it. Users can also add Comment
s to any Block which they can share if other users. I use django-guardian to manage object-based permissions.
I have created a RetrieveAPIView
using Django Rest Framework to make the Document available.
class DocumentDetailView(PermissionRequiredMixin, RetrieveAPIView):
serializer_class = DocumentSerializer
permission_required = "document.view_document"
To include all blocks and their comments in that view, I use the following serializers (omitted class Meta
for brevity):
class DocumentSerializer(serializers.ModelSerializer):
blocks = BlockSerializer(many=True, source="block_set")
class BlockSerializer(serializers.ModelSerializer):
comments = serializers.CommentSerializer(many=True, source="comment_set")
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
I would like to restrict the comments included in DocumentDetailView
to those to which a user has permissions. Following the logic of django-guardian I would use get_objects_for_users()
, to filter down the QuerySet of Block.comment_set.all()
. Yet, I don't know where to do this.
I guess to restrict the comments to those available to request.user
, the permission-based filtering should be done in the DocumentDetailView
, but I don't see how to do this in get_object()
.