我正在尝试在RetrieveUpdateDestroyAPIView中使用get_queryset函数进行原始sql查询。使用ListCreateAPIView()可以正常工作。我是drf的新手。那么请解释一下是否有任何错误。
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
答案 0 :(得分:0)
如果需要,您可能需要覆盖h = plot(NaN,NaN);
axis([0 4*pi -1 1])
x = linspace(0,4*pi,2000);
y = sin(x);
for k = 1:length(x)
set(h, 'XData', x(1:k), 'YData', y(1:k))
drawnow
end
方法。
get_object()
对单个实例执行操作。您可能会尝试评估一下,您真正需要实现的目标以及如何更恰当地完成它。