DRF框架中链表数据通过ModelSerializer深度查询方法汇总
DRF框架中链表数据通过ModelSerializer深度查询方法汇总
一.准备测试和理解准备
创建类
class Test1(models.Model):
id = models.IntegerField(primary_key=True)
test_2_id= models.ForeignKey(to='Test2',on_delete='id') #这里有的创建失败了哈哈忘了会自动补全id
class Test2(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=60)
生成表单数据
Test1
id | test_2_id_id |
---|---|
1 | 1 |
2 | 2 |
Test2
id | name |
---|---|
1 | 名字1 |
2 | 名字2 |
二.深度查询通过Test1获得Test2的name而不是id
方法一
models.py
#对于test1添加方法
class Test1(models.Model):
id = models.IntegerField(primary_key=True)
test_2_id= models.ForeignKey(to='Test2',on_delete='id')
@property
def get_test2_name(self):
return self.test_2_id.name
views.py
from rest_framework.serializers import ModelSerializer
from app.models import Test1
class Test_ser(ModelSerializer):
class Meta:
model = Test1 # 这里会把Test1面的所有名称空间存在的都进行导入
fields = ('id','get_test2_name')
class Test(APIView):
def get(self,request):
test1_objs = Test1.objects.all()
test1_ser = Test_ser(instance=test1_objs,many=True).data
for a in test1_ser:
print(a)
return HttpResponse('ok')
方法二
views.py
from rest_framework.serializers import ModelSerializer
from app.models import Test1,Test2
class Test_2_ser(ModelSerializer):
class Meta:
model = Test2
fields = '__all__'
class Test_ser(ModelSerializer):
test_2_id = Test_2_ser() #test_2_id为Test1与Test2关联的字段
class Meta:
model = Test1
fields = '__all__'
class Test(APIView):
def get(self,request):
test1_objs = Test1.objects.all()
test1_ser = Test_ser(instance=test1_objs,many=True).data
for a in test1_ser:
print(a)
return HttpResponse('ok')
方法三
#通过添加自定义字段
class Test_ser(ModelSerializer):
test_2_name = SerializerMethodField() #自定义字段名称
def get_test_2_name(self,model): #这里方法名必须get_字段名称
return model.test_2_id.name #对于获取字段后的返回值
class Meta:
model = Test1
fields = '__all__'
class Test(APIView):
def get(self,request):
test1_objs = Test1.objects.all()
test1_ser = Test_ser(instance=test1_objs,many=True).data
for a in test1_ser:
print(a)
return HttpResponse('ok')
方法四
#通过添加自定义字段
class Test_ser(ModelSerializer):
image_url=serializers.CharField(source='test_2_id.name') #test1中的test_2_id.name的内容
class Meta:
model = Test1
fields = '__all__'
class Test(APIView):
def get(self,request):
test1_objs = Test1.objects.all()
test1_ser = Test_ser(instance=test1_objs,many=True,context={"request":request}).data
for a in test1_ser:
print(a)
return HttpResponse('ok')