In my application, I have the following models:
class Zone(models.Model): name = models.SlugField() class ZonePermission(models.Model): zone = models.ForeignKey('Zone') user = models.ForeignKey(User) is_administrator = models.BooleanField() is_active = models.BooleanField()
I use the Django REST framework to create a resource that returns information about a zone, as well as a sub-resource that shows the permissions the user has for that zone. The result should be something like this:
{ "name": "test", "current_user_zone_permission": { "is_administrator": true, "is_active": true } }
I created such serializers:
class ZonePermissionSerializer(serializers.ModelSerializer): class Meta: model = ZonePermission fields = ('is_administrator', 'is_active') class ZoneSerializer(serializers.HyperlinkedModelSerializer): current_user_zone_permission = ZonePermissionSerializer(source='zonepermission_set') class Meta: model = Zone fields = ('name', 'current_user_zone_permission')
The problem is that when I request a specific zone, the attached resource returns ZonePermission entries for all users with permissions for that zone. Is there a way to apply a filter to request.user to a nested resource?
BTW I do not want to use HyperlinkedIdentityField for this (to minimize HTTP requests).
Decision
This is a solution that I implemented based on the answer below. I added the following code to my serializer class:
current_user_zone_permission = serializers.SerializerMethodField('get_user_zone_permission') def get_user_zone_permission(self, obj): user = self.context['request'].user zone_permission = ZonePermission.objects.get(zone=obj, user=user) serializer = ZonePermissionSerializer(zone_permission) return serializer.data
Thanks so much for the solution!
django django-rest-framework
David Jones - iPushPull May 29 '13 at 18:51 2013-05-29 18:51
source share