Get current user in Model Serializer

前端 未结 4 668
醉话见心
醉话见心 2021-01-31 14:53

Is it possible to get the current user in a model serializer? I\'d like to do so without having to branch away from generics, as it\'s an otherwise simple task that must be done

4条回答
  •  终归单人心
    2021-01-31 15:17

    I had a similar problem - I tried to save the model that consist user in, and when I tried to use user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault()) like on official documentation - but it throws an error that user is 'null'. Rewrite the default create method and get a user from request helped for me:

    class FavoriteApartmentsSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True, default=serializers.CurrentUserDefault())
    
    class Meta:
        model = FavoriteApartments
        exclude = (
            'date_added',
        )
    
    def create(self, validated_data):
        favoriteApartment = FavoriteApartments(
            apartment=validated_data['apartment'],
            user=self.context['request'].user
        )
        favoriteApartment.save()
        return favoriteApartment
    

提交回复
热议问题