Quantcast
Channel: User Christoffer - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Answer by Christoffer for How can I apply a filter to a nested resource in Django REST framework?

$
0
0

I would do it in one of two ways.

1) Either do it through prefetch in your view:

    serializer = ZoneSerializer(Zone.objects.prefetch_related(
        Prefetch('zone_permission_set', 
            queryset=ZonePermission.objects.filter(user=request.user), 
            to_attr='current_user_zone_permission'))
        .get(id=pk))

2) Or do it though the .to_representation:

class ZoneSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Zone
        fields = ('name',)

    def to_representation(self, obj):
        data = super(ZoneSerializer, self).to_representation(obj)
        data['current_user_zone_permission'] = ZonePermissionSerializer(ZonePermission.objects.filter(zone=obj, user=self.context['request'].user)).data
        return data

Viewing all articles
Browse latest Browse all 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>