我正在尝试将一些response_body中的数据添加到数据库“仪表板”中的“进攻”表中
我只想添加一次此数据,所以在第一次将数据成功添加到我的数据库后,却给了我这个错误,因为它显然拒绝为另一个设置为唯一的oid创建重复条目< / p>
如何修改我的代码,以便仅添加一次数据且不添加重复数据,并且不会出现此错误django.db.utils.IntegrityError: (1062, "Duplicate entry '4767' for key 'PRIMARY'")
下面是我的代码。 我已经从models.py创建了表格,并从views.py添加了数据,因为该数据存在于views.py中,并且从此处添加数据更加容易。
如果还有其他合适的方法,请提出建议。
models.py
from django.db import models
from django.contrib.auth.models import UserManager
from django.core.validators import int_list_validator
# Create your models here.
class Offenses(models.Model):
oid = models.IntegerField(primary_key=True)
description = models.CharField(null=False, max_length=20)
assigned_to = models.CharField(null=True, max_length=20)
categories = models.TextField(null=True)
category_count = models.IntegerField(null=True)
policy_category_count = models.IntegerField(null=True)
security_category_count = models.IntegerField(null=True)
close_time = models.TimeField(null=True)
closing_user = models.IntegerField(null=True)
closing_reason_id = models.IntegerField(null=True)
credibility = models.IntegerField(null=True)
relevance = models.IntegerField(null=True)
severity = models.IntegerField(null=True)
magnitude = models.IntegerField(null=True)
destination_networks = models.TextField(null=True)
source_network = models.CharField(null=True, max_length=20)
device_count = models.IntegerField(null=True)
event_count = models.IntegerField(null=True)
flow_count = models.IntegerField(null=True)
inactive = models.BooleanField(null=True)
last_updated_time = models.DateTimeField(null=True)
local_destination_count = models.IntegerField(null=True)
offense_source = models.IntegerField(null=True)
offense_type = models.IntegerField(null=True)
protected = models.BooleanField(null=True)
follow_up = models.BooleanField(null=True)
remote_destination_count = models.IntegerField(null=True)
source_count = models.IntegerField(null=True)
start_time = models.TimeField(null=True)
status = models.CharField(null=True, max_length=20)
username_count = models.IntegerField(null=True)
source_address_ids = models.TextField(null=True)
local_destination_address_ids = models.TextField(null=True)
domain_id = models.IntegerField(null=True)
objects = UserManager()
class Meta:
db_table = "offenses"
views.py
response_body = json.loads(response.read().decode('utf-8'))
for j in response_body:
obj = Offenses.objects.create(oid=j['id'], description=j['description'])
答案 0 :(得分:0)
使用Django的get_or_create:
obj, created = Offenses.objects.get_or_create(oid=j['id'], defaults={'description': j['description']})