Skip to content

Instantly share code, notes, and snippets.

@nezort11
Created February 13, 2022 19:03
Show Gist options
  • Save nezort11/8cef81d617edf0da5f86f61591b7a22d to your computer and use it in GitHub Desktop.
Save nezort11/8cef81d617edf0da5f86f61591b7a22d to your computer and use it in GitHub Desktop.
""" 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"]
@nezort11
Copy link
Author

If the user doesn't have permission to some related object, he will just not be able to see it at all, sample error

401 Bad request
{
  "obj": [
    "Invalid pk \"1\" - object does not exist."
  ]
}

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment