Home > OS >  Limit serializer by user
Limit serializer by user

Time:01-31

Here is my model serializer:

class FoodImagesSerializerGet(serializers.ModelSerializer):
    current_user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    food = serializers.SlugRelatedField(
        many=False, read_only=False,slug_field='id', queryset=Food.objects.filter(users=current_user)
    )

Model:

class FoodImages(models.Model):
    food = models.ForeignKey(Food, related_name='food_images', related_query_name='food_image', on_delete=models.CASCADE, null=True)
class Food(models.Model):
        users = models.ManyToManyField(
        Profile,
        related_name='userfoods',
        related_query_name='userfood',
    )

I want to limit the serializer by users so only the users of the food can post images . I want to do that Just with the SlugRelatedField

CodePudding user response:

You can override SlugRelatedField like this:

class CustomSlugRelatedField(SlugRelatedField):
    def get_queryset(self):
        return self.queryset.filter(users=self.context['request'].user)

class FoodImagesSerializerGet(serializers.ModelSerializer):
    food = CustomSlugRelatedField(
        many=False, read_only=False,slug_field='id', queryset=Food.objects.all()
    )

Finally, you need to pass the request via context in the serializer. This is taken cared by the GenericViews and ModelViewSets automatically, for function based view, you can try like this:

serializer = FoodImagesSerializerGet(Food.objects.first(), context={'request': request})

CodePudding user response:

it's a class attribute, it couldn't access to request context on runtime. You have to access it via init method

class FoodImagesSerializerGet(serializers.ModelSerializer):
    current_user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    food = serializers.SlugRelatedField(
        many=False, read_only=False,slug_field='id', queryset=Food.objects.all()
    )

    def __init__(self, *args, **kwargs):
        self.fields['food'].queryset = Food.objects.filter(users=self.context['request'].user)
  • Related