在返回之前替换queryset中的字段

时间:2014-08-30 17:21:23

标签: django django-rest-framework

我有以下观点 -

class DeployFilterView(generics.ListAPIView):
    serializer_class = DefinitionSerializer

    def get_queryset(self):
        jobname = self.request.GET.get('jobname')
        if jobname.count("\\") == 1:
            jobname = jobname.replace("\\", "")
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_name=jobname).exclude(jobmst_prntname__isnull=False, jobmst_dirty='X')
        else:
            parent, job = jobname.rsplit('\\', 1)
            queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_prntname=parent, jobmst_name=job).exclude(jobmst_dirty='X')
        return queryset

在该视图中,有一个名为“jobmst_runbook”的值字段,其字符不能与DRF XML渲染器一起转换。我希望能够做的是扫描查询集中的特定字符 - SOH或\ u0001

如果找到此字符,我想在执行return queryset

之前将其删除

1 个答案:

答案 0 :(得分:1)

我通过在序列化程序中执行逻辑来解决这个问题。序列化程序现在正在寻找导致失败并剥离角色的对象。

class DefinitionSerializer(serializers.ModelSerializer):
    runbook_url = serializers.SerializerMethodField('get_url')
#    dependencies = serializers.RelatedField(many=True)
    jobdep = serializers.HyperlinkedRelatedField(
        source='jobdep_set', # this is the model class name (and add set, this is how you call the reverse relation of bar)
        view_name='jobdep-detail' # the name of the URL, required
    )
#    triggers = serializers.RelatedField(many=True)
    trgmst = serializers.HyperlinkedRelatedField(
        source='trgmst_set', # this is the model class name (and add set, this is how you call the reverse relation of bar)
        view_name='trgmst-detail' # the name of the URL, required
    )

    class Meta:
        model = Jobmst
        resource_name = 'jobmst'
        depth = 2
        fields = ('jobmst_id', 'jobmst_type', 'jobmst_prntid', 'jobmst_active', 'evntmst_id',
                    'jobmst_evntoffset', 'jobmst_name', 'jobmst_mode', 'jobmst_owner', 'jobmst_desc',
                    'jobmst_crttm', 'jobdtl_id', 'jobmst_lstchgtm', 'runbook_url', 'jobcls_id', 'jobmst_prntname',
                    'jobmst_alias', 'jobmst_dirty', 'job_dependencies', 'job_events')

    def get_url(self, obj):
        if obj.jobmst_runbook == None:
            pass
        else:
            return force_text(obj.jobmst_runbook[:-5])