Created
February 13, 2022 19:03
-
-
Save nezort11/8cef81d617edf0da5f86f61591b7a22d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Custom serializer related field filtering based on request user. | |
""" | |
class Model1RelatedField(serializers.PrimaryKeyRelatedField): | |
"""Custom Model1 related field that filters queryset based on requesting user. | |
It is REQUIRED for filter-based permission on related object. | |
On needed for create and update actions bacause they choose form serializer related field.. | |
""" | |
def get_queryset(self): | |
user = self.context["request"].user | |
return Model1.objects.filter(user=user) | |
class Model2CreateSerializer(serializers.ModelSerializer): | |
obj = Model1RelatedField() | |
class Meta: | |
model = Model2 | |
fields = ["obj"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the user doesn't have permission to some related object, he will just not be able to see it at all, sample error
In my opinion, explicit filtering is better than "filter and then perform check" though sometimes the filter can get really long (because you need to nest filtering from the previous serializer).