美文网首页
Django序列化 source指定外键表字段来源

Django序列化 source指定外键表字段来源

作者: 梨花菜 | 来源:发表于2020-08-23 12:59 被阅读0次

    model

    # case_step model
    class CaseStep():
       class Meta:
            db_table = "case_step"
    
        name = models.CharField("用例名称", null=False, max_length=100)
        # Case主键作为外键
        case = models.ForeignKey(Case, on_delete=models.CASCADE, db_constraint=False)
        source_api_id = models.IntegerField("api来源", null=False)
    
    # case model
    class Case(BaseTable):
       class Meta:
            db_table = "case"
       name = models.CharField("用例名称", null=False, max_length=100)
        ...
        tag = models.IntegerField("用例标签", choices=tag, default=2)
    

    序列化

    class APISerializer(serializers.ModelSerializer):
        cases = serializers.SerializerMethodField()
    
        class Meta:
            model = models.API
            # fields = '__all__'
            fields = ['id', 'name',..., 'cases']
        def get_cases(self, obj):
            # 查询副表,为了获取case_id
            cases = models.CaseStep.objects.filter(source_api_id=obj.id)
           # 通过自定义字段来源的序列化返回case model中的case_name, case_id
            case_id = APIRelatedCaseSerializer(many=True, instance=cases)
            return case_id.data
    
    class APIRelatedCaseSerializer(serializers.Serializer):
        # 指定字段来源是case model中的name, case要用小写,对应case model中的db_name
        case_name = serializers.CharField(source='case.name')  
        case_id = serializers.CharField(source='case.id')
    
        class Meta:
            fields = ['case_id', 'case_name']
    

    相关文章

      网友评论

          本文标题:Django序列化 source指定外键表字段来源

          本文链接:https://www.haomeiwen.com/subject/fdvijktx.html