I have a working code which gets all incident details. But i am unable to save complete data in database only the last record gets saved
def incidents(request):
incidentsServicenow = IncidentsServicenow()
c = pysnow.Client(instance='', user='', password='')
# Define a resource, here we'll use the incident table API
incident = c.resource(api_path='/table/incident')
print('incident', incident)
# Query for incidents with state 1
response = incident.get()
print('response', response)
# Iterate over the result and print out `sys_id` of the matching records.
ticket = []
for record in response.all():
data = {
'number': record['number'],
'description': record['description'],
'short_description': record['short_description'],
'state': record['state'],
}
#print(record['number'])
incidentsServicenow.number = data['number']
incidentsServicenow.title = data['short_description']
incidentsServicenow.description = data['description']
incidentsServicenow.state = data['state']
#ticket.append(data)
print("storing data")
incidentsServicenow.save()
return HttpResponse(ticket, content_type='application/json')
My model is
class IncidentsServicenow(models.Model):
number = models.CharField(max_length=32)
title = models.CharField(max_length=160)
description = models.TextField()
state = models.CharField(max_length=20)
class Meta:
managed = False
db_table = 'incidents_servicenow'
I need to save all the records in database
You should create objects in the loop. From the code, I can see that you created the incidentsServicenow
object is created outside the loop.
for record in response.all():
data = {
'number': record['number'],
'description': record['description'],
'short_description': record['short_description'],
'state': record['state'],
}
#print(record['number'])
incidentsServicenow = IncidentsServicenow()
incidentsServicenow.number = data['number']
incidentsServicenow.title = data['short_description']
incidentsServicenow.description = data['description']
incidentsServicenow.state = data['state']
ticket.append(data)
print("storing data")
incidentsServicenow.save()
return HttpResponse(ticket, content_type='application/json')
or you could do like this
for record in response.all():
data = {
'number': record['number'],
'description': record['description'],
'short_description': record['short_description'],
'state': record['state'],
}
#print(record['number'])
incidentsServicenow = IncidentsServicenow(number=data['number'],
title=data['short_description'],description=data['description'],state=data['state'])
ticket.append(data)
print("storing data")
incidentsServicenow.save()
return HttpResponse(ticket, content_type='application/json')