0
我想在RetrieveUpdateDestroyAPIView中對原始sql查詢使用get_queryset函數。這與ListCreateAPIView()工作正常。我是drf的新手。所以,請解釋一下是否有什麼事情做錯了。get_queryset不適用於drf RetrieveUpdateDestroyAPIView
views.py
class SubnetGatewayDevice(generics.ListCreateAPIView):
serializer_class = SubnetDeviceSerializer
def get_queryset(self):
sql_query = " select sd.hostname,sd.ma_number,sd.datacenter_id, ssd.ip, ssp.subnet_id, " \
" sd.id, ssd.id, ssp.id from subnets_device sd" \
" inner join subnets_subnetdevice as ssd on sd.id = ssd.device_id" \
" inner join subnets_subnetphysical as ssp on ssd.subnet_physical_id = ssp.id"
return list(Device.objects.raw(sql_query))
def perform_create(self, serializer):
serializer.save(data=self.request.data)
class SubnetGatewayDeviceDetail(generics.RetrieveUpdateDestroyAPIView):
# parser_classes = (JSONParser,)
serializer_class = SubnetDeviceSerializer
def get_queryset(self):
device_id = "5"
sql_query = " select sd.hostname as hostname,sd.ma_number,sd.datacenter_id, ssd.ip, ssp.subnet_id, " \
" sd.id, ssd.id, ssp.id from subnets_device sd" \
" inner join subnets_subnetdevice as ssd on sd.id = ssd.device_id" \
" inner join subnets_subnetphysical as ssp on ssd.subnet_physical_id = ssp.id " \
" where sd.id = "+device_id
return Device.objects.raw(sql_query)
# def perform_create(self, serializer):
# serializer.save(data=self.request.data)
Serializer.py
class SubnetDeviceSerializer(serializers.ModelSerializer):
subnet_id = serializers.IntegerField(required=True)
datacenter_id = serializers.IntegerField(required=True)
ip = serializers.IPAddressField(protocol='both')
class Meta:
model = Device
fields = ('id','hostname','ma_number','subnet_id','datacenter_id','ip')
def create(self, validated_data):
subnet_id = validated_data['subnet_id']
ma_number = validated_data['ma_number']
hostname = validated_data['hostname']
data_center_id = validated_data['datacenter_id']
gateway_ip= validated_data['ip']
subnet_physical = SubnetPhysical.objects.get(subnet_id=subnet_id)
if subnet_physical:
subnet_physical_id = subnet_physical.id
device_obj = Device()
device_obj.hostname = hostname
device_obj.ma_number = ma_number
device_obj.datacenter_id = data_center_id
device_obj.save()
device_pk = device_obj.id
subnet_device_obj = SubnetDevice()
subnet_device_obj.ip = gateway_ip
subnet_device_obj.device_id = device_pk
subnet_device_obj.subnet_physical_id = subnet_physical_id
subnet_device_obj.save()
return device_pk
感謝您的回覆。我能舉個例子嗎? – Anish
好吧。那麼如果我們有一個RetrieveUpdateDestroyAPIView的自定義查詢。因爲我的輸出是連接多個表 – Anish
您原始SQL查詢似乎與ListCreateAPIView,然後我想你不需要對RetrieveUpdateDestroyAPIView做任何事情。你只是通過ID作爲參數,其餘的將被照顧。 – zaidfazil