django中模型的序列化的作用有哪些

  介绍

今天就跟大家聊聊有关django中模型的序列化的作用有哪些,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一直对使用DRF的了解停留在一知半解的状态,今天在实际操作中,感受到了DRF带来的方便

django工程,其中两个模型定义如下:

AutomationHeadRaw:   类AutomationHeadRaw (models.Model):   “““   测试用例的请求的json形式参数   “““   id=models.AutoField (primary_key=True)   automationCaseApi=模型。一对一字段(AutomationCaseApi related_name=& # 39; headRaw& # 39;,   on_delete=模型。级联,verbose_name=& # 39;接口& # 39;)   data=https://www.yisu.com/zixun/models.TextField (verbose_name='源数据请求头json数据的,空白=True, null=True)      类元:   verbose_name='请求头json格式参数的   verbose_name_plural='请求头json格式参数管理”

AutomationCaseApi:

类AutomationCaseApi (models.Model):
  “““
  用例执行接口
  “““
  id=models.AutoField (primary_key=True)
  automationTestCase=模型。ForeignKey (AutomationTestCase>类AutomationCaseApiSerializer (serializers.ModelSerializer):
  “““
  自动化用例接口详细信息序列化
  “““
  头=AutomationHeadSerializer(许多=True, read_only=True)
  headRaw=AutomationHeadRawSerializer(许多=False, read_only=True) #一对一表格,变量名一定要和模型定义relate-name一直
  parameterList=AutomationParameterSerializer(许多=True, read_only=True)
  parameterRaw=AutomationParameterRawSerializer(许多=False, read_only=True)
  类元:
  模型=AutomationCaseApi
  字段=(& # 39;id # 39; & # 39;名字# 39;,& # 39;httpType& # 39;, & # 39; requestType& # 39;, & # 39; apiAddress& # 39;, & # 39;头# 39;,& # 39;具有# 39;,& # 39;requestParameterType& # 39;,
  & # 39;headRaw& # 39; & # 39; formatRaw& # 39; & # 39; parameterList& # 39;, & # 39; parameterRaw& # 39; & # 39; examineType& # 39;, & # 39; httpCode& # 39; & # 39; responseData& # 39;, & # 39; preFun& # 39;
  & # 39;afterFun& # 39; & # 39; skipFlag& # 39; & # 39; stopFlag& # 39;, & # 39; retryNum& # 39;) 

则获取模型AutomationCaseApi可以自动转换:

自我。case_data=https://www.yisu.com/zixun/AutomationCaseApiSerializer (
AutomationCaseApi.objects.get (id=self.case_api_id automationTestCase=self.case_id))。数据

3,因此上面的AutomationHeadRaw可以通过添加模型序列化类AutomationHeadRawSerializer自动转换数据格式:
类AutomationHeadRawSerializer (serializers.ModelSerializer):

自动化用例接口json类型请求头信息序列化

类元:
模型=AutomationHeadRaw
字段=(& # 39;id # 39; & # 39; automationCaseApi& # 39;, & # 39;数据# 39;)

获取数据语句可以改成,不需要手工转换:
头=AutomationHeadRawSerializer (
AutomationHeadRaw.objects.filter (automationCaseApi=self.case_api_id),
许多=True)。数据

注意:

上面获取数据的AutomationHeadRawSerializer()方法,入参1:AutomationHeadRaw.objects.filter (automationCaseApi=self.case_api_id)

可以为两种对象:

AutomationHeadRaw.objects.filter (automationCaseApi=self.case_api_id)(过滤方法对象为queryset类型)
AutomationCaseApi.objects.get (id=自我。case_api_id automationTestCase=self.case_id)(得到方法对象为模型类类型)

看完上述内容,你们对django中模型的序列化的作用有哪些有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。

django中模型的序列化的作用有哪些