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

2020-08-23  本文已影响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']
上一篇下一篇

猜你喜欢

热点阅读