psycopg2.IntegrityError:重复的键值违反了唯一约束“ engine_attackimage_pkey”详细信息:键(id)=(19)已存在

时间:2019-12-14 22:23:48

标签: python django

我没有手动设置主键。这怎么可能发生?

相关代码:

        for im_url in image_urls:
            print(im_url)
            if im_url.split('.')[-1] != 'gif' and '/' in im_url.split('.com/')[1]:
                img_temp = NamedTemporaryFile(delete=True)
                img_temp.write(urllib.request.urlopen(im_url).read())
                img_temp.flush()

                img_filename = slugify(im_url.split('.com/')[1].split('/')[1])[:50]
                print(img_filename)
                try:
                    attack_image_object = AttackImage.objects.create(
                        title=img_filename,
                        source_url=im_url,
                        creator=mike
                    )
                except Exception as e:
                    print(e)
                    continue
                attack_image_object.image.save(img_filename, File(img_temp))

                attack_item_object = AttackItem.objects.create(
                    attack_image=attack_image_object,
                    attack='SPA',
                    creator=mike,
                )
                attack_item.hidden_data_found = (attacks.spa(attack_image.image) > 0.05)
                attack_item.save()

                print('%s created' % (img_filename))

模型


class AttackImage(models.Model):
    title = models.CharField(max_length=255)
    image = models.ImageField(upload_to='attack_images', blank=True, null=True)
    source_url = models.URLField(blank=True,null=True)
    domain = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True)
    creator = models.ForeignKey(User, on_delete=models.CASCADE, blank=True,null=True)
    slug = models.SlugField(blank=True,null=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)[:50]

        if self.source_url and not self.image:
            result = urllib.request.urlretrieve(self.source_url)
            self.image.save(
                    os.path.basename(self.source_url),
                    File(open(result[0], 'rb'))
                    )
        if self.source_url:
            if '//' in self.source_url:
                d = self.source_url.split('//')[1].split('/')[0]
            else:
                d = self.source_url.split('/')[0]

            try:
                domain = Domain.objects.get(domain_url=d)
            except Exception as e:
                print(e)
                domain_object = Domain.objects.create(domain_url=d)
                domain = domain_object
            self.domain = domain

        return super(AttackImage, self).save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("attack_image_detail", kwargs={
            'pk': str(self.id),
            'slug': str(self.slug)})

回溯

Traceback (most recent call last):
  File "crawl_ebaumsworld.py", line 91, in <module>
    crawl(first_url)
  File "crawl_ebaumsworld.py", line 65, in crawl
    creator=mike
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 422, in create
    obj.save(force_insert=True, using=self.db)
  File "/home/michael/projects/deepsteg/engine/models.py", line 64, in save
    return super(AttackImage, self).save(*args, **kwargs)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
    force_update, using, update_fields,
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
    result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
    using=using, raw=raw)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1335, in execute_sql
    cursor.execute(sql, params)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/home/michael/projects/deepsteg/venvdeepsteg/lib/python3.6/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "engine_attackimage_pkey"
DETAIL:  Key (id)=(19) already exists.

在Django的5年编程经验中,我从未遇到过这个错误。仅查看代码和回溯,就无法判断出问题所在。有什么事吗让我知道是否需要发布更多代码。提前致谢。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

您正在尝试使用保存方法保存子模型。

self.image.save(
                os.path.basename(self.source_url),
                File(open(result[0], 'rb'))
                )

因此,您需要在调用super的save方法之前保存模型。在调用super的save方法之前,应该设置图像但不保存。

self.image = os.path.basename(self.source_url),File(open(result[0], 'rb'))

答案 1 :(得分:0)

我想可能的解决方法是:

./manage.py migrate appname zero

用您的应用程序名称修改应用程序名称。 然后:

python manage.py migrate --run-syncdb