django - django 无法将所有事件保存在数据库中
问题描述
我有一个可以获取所有事件详细信息的工作代码。但我无法在数据库中保存完整的数据,只有最后一条记录被保存
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'
我需要将所有记录保存在数据库中
解决方案
您应该在循环中创建对象。从代码中,我可以看到你创建的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')
推荐阅读
- android - 反应原生android模拟器错误:无法安装应用程序
- xamarin - 本机链接失败
- django-rest-framework - 哪种架构最适合多个用户编辑同一数据库记录?
- c++ - 当您将带有字符串索引的地图索引设置为另一个字符串索引值时会发生什么?
- wordpress - 将 Bootstrap css 添加到 wordpress 管理区域而不添加主要 style.css
- r - 带有下划线分隔符的纳米时间格式,用于小数秒
- android-jetpack-compose - 如何在 Kotlin Compose 桌面中从远程 url 加载图像?
- linux - 我在哪里可以找到使用 GDB 和 QEMU 的过程控制块 (PCB) 和 GDTR/LDTR 内容?
- python - 获取该字段的 xpath
- javascript - fetch() 失败时函数停止