django 按用户限制序列化程序

hgqdbh6s  于 2023-01-31  发布在  Go
关注(0)|答案(2)|浏览(115)

下面是我的模型序列化器:

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

型号:

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',
    )

我想通过用户来限制序列化器,这样只有食物的用户才能发布图片。我想这样做,就用SlugRelatedField

xmakbtuz

xmakbtuz1#

您可以像这样覆盖SlugRelatedField:

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

最后,你需要通过序列化器中的上下文传递request。这是由GenericViews和ModelViewSets自动处理的,对于基于函数的视图,你可以这样尝试:

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

sqxo8psd2#

这是一个类属性,它不能在运行时访问请求上下文。您必须通过init方法访问它

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)

相关问题