Django 多对多正查,反查,序列化
2020-08-22 本文已影响0人
梨花菜
Python 3.6.8
Django==2.2
djangorestframework 3.11.1
1.Models
1.1 母表
class Case():
class Meta:
db_table = "case"
name = models.CharField("用例名称", null=False, max_length=100)
...
apis = models.ManyToManyField(API, db_table='api_case', related_name='api_case_relate')
1.2 子表
class API(BaseTable):
"""
API信息表
"""
class Meta:
db_table = "api"
name = models.CharField("接口名称", null=False, max_length=100, db_index=True)
...
2.查询和序列化
2.1母表查询
# api_case 是api和case的关系表
# 使用子表的字段在关系表中查询
Case.objects.filter(apis__id=3736).all()
sql等于
SELECT case.* FROM `case` INNER JOIN `api_case` ON (`case`.`id` = `api_case`.`case_id`) WHERE `api_case`.`api_id` = 'xxx'
# 使用目表的条件在关系表中查询
Case.objects.get(id=169).apis.all()
sql等于
SELECT api.* FROM `api` INNER JOIN `api_case` ON (`api`.`id` = `api_case`.`api_id`) WHERE `api_case`.`case_id` = 'xxx'
2.2主表序列化
class CaseSerializer(serializers.ModelSerializer):
"""
用例信息序列化
"""
apis = serializers.PrimaryKeyRelatedField(queryset=models.API.objects.all(), many=True)
class Meta:
model = models.Case
fields = '__all__'
2.3子表查询
# api_case_relate 是 Case Model中的related_name
# 使用母表的字段查询在关系表中查询
API.objects.get(pk='xxx').api_case_relate.all()
sql等于
SELECT api.* FROM `api` INNER JOIN `api_case` ON (`api`.`id` = `api_case`.`api_id`) WHERE `api_case`.`case_id` = 'xxx'
# 在关系表中使用子表的字段查询
API.objects.get(pk=3736).api_case_relate.all()
sql等于
SELECT case.* FROM `case` INNER JOIN `api_case` ON (`case`.`id` = `api_case`.`case_id`) WHERE `api_case`.`api_id` = 'xxx'
2.4子表序列化
class APISerializer(serializers.ModelSerializer):
# 使用钩子方法序列化
cases = serializers.SerializerMethodField()
# 使用目表的序列化器,很多地方这么说,但我试了不行.
# cases = CaseSerializer(many=True, read_only=True)
class Meta:
model = models.API
# fields = '__all__'
fields = ['id', 'name',..., 'cases']
def get_cases(self, obj):
cases = obj.api_case_relate.all()
case_id = CaseSerializer(many=True, instance=cases)
return case_id.data