DRF框架中鏈表數據通過ModelSerializer深度查詢方法彙總 一.準備測試和理解準備 創建類 生成表單數據 Test1 id| test_2_id_id | 1|1 2|2 Test2 id|name | 1|名字1 2|名字2 二.深度查詢通過Test1獲得Test2的name而不是id ...
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')