我的'@angular/platform-browser'
中有一个自定义验证功能,用于检查两个参数(mrange,mthreshold)。验证功能检查在发布时只需要设置其中一个参数。
# check base diectory provided exists
[ -e "$1" ] || {
printf "\nError: invalid path. \n\n"
exit 1
}
# find the files in base directory, sort them and filter out uniques, and iterate over the resulting list of files
# note: we're only filtering .json files here
for name in `find $1 -type f -printf "%f\n" | sort | uniq -d`;
do
# we keep count of the duplicate files for a file to keep track of the last file(biggest in size)
numDups=$(find $1 -name $name | wc -l); # number of duplicates found for a given file
for file in $(find $1 -name $name | sort -h); # sort the files again on basis of size
do
if [ $numDups -ne 1 ];
then
if [ "$option" = -d ] # remove the duplicate file
then
rm $file
else
echo $file # if -d is not provided, just print the duplicate file names
# note: this will print only the duplicate files, and not the latest/biggest file
fi
fi
numDups=$(($numDups-1))
# note: as per current code, we are checking options value for each duplicate file
# we can move the if conditions out of the for loop, but that would need duplication of code
# we may try modifying the script otherwise, if we see serious performance issues.
done
done;
exit 0;
在我的views.py文件中
DataSerliazer
目前,我必须编写anthor class DataSerializer(serializers.ModelSerializer):
emails = serializers.ListField(child = serializers.EmailField())
class Meta:
model = AIData
fields = ('id', 'name', 'created', 'username', 'token',
'expression','key','threshold' ,'evaluator', 'range','emails','metric_name', 'status')
def validate(self,attrs):
mrange = attrs.get("metric_range")
mthreshold = attrs.get("metric_threshold")
if (mrange == None or mrange == " ") and (mthreshold == None or mthreshold == " "):
raise serializers.ValidationError({'error': 'Cannot have both range and threshold empty'})
elif mrange != None and mthreshold != None:
raise serializers.ValidationError({'error': 'Cannot set both range and threshold'})
,以便它不会隐式调用DataSerializer中的validate函数。这是为了避免在对象创建期间检查2个参数。一旦创建了对象,我就不想再检查相同的功能了。有没有更简洁的方式做同样的事情?我最好避免为同一型号编写2个Serializer。
答案 0 :(得分:0)
据我所知,rest-framework库没有这样的东西。
我这样做是为了覆盖__init__
并添加你自己的变量来检查它。
class DataSerializer(serializers.ModelSerializer):
emails = serializers.ListField(child = serializers.EmailField())
class Meta:
model = AIData
fields = ('id', 'name', 'created', 'username', 'token',
'expression','key','threshold' ,'evaluator', 'range','emails','metric_name', 'status')
def __init__(self, *args, **kwargs):
super(DataSerializer, self).__init__(*args, **kwargs)
self._request_method = kwargs.get('request_method', 'GET')
def validate(self,attrs):
if self._request_method == 'GET':
# GET logic
elif self._request_method in ('PUT', 'POST'):
# Put or Post logic
然后我会像这样使用它:
serializer = DataSerializer(ai, request_method=request.method)
答案 1 :(得分:0)
您可以将context
data传递给可能包含请求本身的序列化程序。
您可以通过调用self.context来随时随地访问序列化程序中的上下文。
此解决方案确实可以更轻松地提供上下文数据,而无需覆盖__init__
。