@api_view(['GET'])
def selected_device(request,pk=None):
if pk != None:
devices = Device.objects.filter(pk=pk)
devicedetail = DeviceDetail.objects.filter(DD2DKEY=pk)
cursor = connection.cursor()
tablename= "dev_interface_" str(pk)
cursor.execute(f"SELECT interface FROM {tablename} ")
righttable = cursor.fetchall()
devserializer = DeviceSerializers(devices, many=True)
devdserializer = DeviceDetailSerializers(devicedetail, many=True)
interfaces = []
for i in righttable:
interfaces.append(i[0])
for i in interfaces:
data =[{"interface": i}]
interserializer = InterfaceSerializers(data, many = True)
results = {
"device":devserializer.data,
"device_details" : devdserializer.data,
"interface":interserializer.data,
}
return Response(results)
In interfaces
, I have the following ['G0/1', 'TenGigabitEthernet1/1/3', 'TenGigabitEthernet1/1/5', 'TenGigabitEthernet1/1/20', 'TenGigabitEthernet1/1/21', 'TenGigabitEthernet1/1/22', 'TenGigabitEthernet1/1/23', 'TenGigabitEthernet1/1/24', 'TenGigabitEthernet1/1/25', 'TenGigabitEthernet1/1/26']
But the above codes just print the last item in interface
, how do I ensure it to print everything in interface?
CodePudding user response:
You write
for i in interfaces:
data = [{"interface": i}]
which means you keep on overwriting data
with a new value. I think you want:
data = []
for i in interfaces:
data.append({"interface": i})
or more simply
data = [{"interace": i} for i in interfaces]