简体   繁体   中英

How do I dynamically filter fields returned in django rest api get request based on the user making the request?

I have a photoshoot api that allows photographers to post shoot photos from which preview and watermarded versions are derived. Editors and clients can both select which photos will be edited, but the editor should only see the preview without watermark and the clients should only see the watermarked versions.
I was wondering how these different distincitons can be made in the DRF queryset.
My model:


class Unedited(models.Model):
    shoot = models.ForeignKey(
        Shoot, on_delete=models.CASCADE, null=True, related_name="shoot_photo"
    )
    original = models.ImageField(null=True, blank=False, upload_to=shoot_upload_to)
    preview = models.ImageField(null=True, blank=True, upload_to=shoot_upload_to)
    watermarked = models.ImageField(null=True, blank=True, upload_to=shoot_upload_to)
    upload_time = models.DateTimeField(auto_now_add=True)

My Serializer:


class UneditedSerializer(serializers.ModelSerializer):
    class Meta:
        model = Unedited
        fields = "__all__"

    def create(self, validated_data):
        validated_data["preview"] = reduce_resolution(validated_data["original"])
        validated_data["watermarked"] = add_watermark(validated_data["preview"])
        img_obj = Unedited.objects.create(**validated_data)
        img_obj.save()
        return img_obj

My view:


class UneditedViewSet(viewsets.ModelViewSet):
    if not TESTING:
        permission_classes = (PhotosPermission,)
    serializer_class = UneditedSerializer

    def get_queryset(self):
        return Unedited.objects.filter(**self.request.query_params)

I was able to solve this issue by creating separate serializers with different fields for the different cases. UneditedSerializer remained as is but I created other serializers:


class UneditedMarkedSerializer(serializers.ModelSerializer):
    class Meta:
        model = Unedited
        fields = ("watermarked", "shoot", "upload_time")


class UneditedPreviewSerializer(serializers.ModelSerializer):
    class Meta:
        model = Unedited
        fields = ("preview", "shoot", "upload_time")

I then modified the viewset to check against the user making the request to determine which serializer to use. Like so:


class UneditedViewSet(viewsets.ModelViewSet):
    if not TESTING:
        permission_classes = (PhotosPermission,)
    serializer_class = UneditedSerializer

    def get_queryset(self):
        return generic_queryset(Unedited, self.request.query_params)

    def list(self, request):
        queryset = self.get_queryset()
        if request.user.is_anonymous or request.user.role == "CLIENT":
            serializer = UneditedMarkedSerializer(queryset, many=True)
        elif request.user.role == "EDITOR":
            print(request.user.role)
            serializer = UneditedPreviewSerializer(queryset, many=True)
        elif request.user.role in ("ADMIN", "STAFF"):
            serializer = UneditedSerializer(queryset, many=True)
        return Response(serializer.data)

And now it works as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM