django无法将所有事件保存在数据库中

时间:2019-03-04 06:50:16

标签: django django-database django-datatable django-database-functions

我有一个可以获取所有事件详细信息的有效代码。 但是我无法将完整的数据保存到数据库中,只有最后一条记录被保存了

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')

我的模特是

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'

我需要将所有记录保存在数据库中

2 个答案:

答案 0 :(得分:1)

您应该在循环中创建对象。从代码中,我可以看到您创建的incidentsServicenow对象是在循环外部创建的。

  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')

或者您可以这样做

   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')

答案 1 :(得分:1)

在for循环内添加以下行

incidentsServicenow = IncidentsServicenow()