# Buggy code
def store_dnsbl_result(self, domain, provider, results, **options):
    """Store DNSBL provider results for domain."""
    alerts = {}
    to_create = []
    for mx in results.keys():
        result = "" if not results[mx] else results[mx]
        dnsbl_result = models.DNSBLResult.objects.filter(
            domain=domain, provider=provider, mx=mx
        ).first()
        trigger = False
        if dnsbl_result is None:
            to_create.append(
                models.DNSBLResult(
                    domain=domain, provider=provider, mx=mx, status=result
                )
            )
            if result:
                trigger = True
        else:
            dnsbl_result.status = result
            dnsbl_result.save()
            if not dnsbl_result.status and result:
                trigger = True
        if trigger:
            if domain not in alerts:
                alerts[domain] = []
            alerts[domain].append((provider, mx))
    models.DNSBLResult.objects.bulk_create(to_create)
    if not alerts:
        return
    emails = list(options["email"])
    if not options["skip_admin_emails"]:
        emails.extend(
            domain.admins.exclude(mailbox__isnull=True).values_list("email", flat=True)
        )
    if not len(emails):
        return
    with mail.get_connection() as connection:
        for domain, providers in list(alerts.items()):
            content = render_to_string(
                "admin/notifications/domain_in_dnsbl.html",
                {"domain": domain, "alerts": providers},
            )
            subject = _("[modoboa] DNSBL issue(s) for domain {}").format(domain.name)
            msg = EmailMessage(
                subject, content.strip(), self.sender, emails, connection=connection
            )
            msg.send()


# Traceback (django.db.utils.IntegrityError)
Traceback (most recent call last):
File "/srv/modoboa/instance/manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
utility.execute()
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py", line 53, in run_from_argv
return super(SubcommandCommand, self).run_from_argv(argv)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/srv/modoboa/env/lib/python2.7/site-packages/subcommand/base.py", line 84, in handle
return command.run_from_argv(argv)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/core/management/base.py", line 345, in execute
output = self.handle(*args, **options)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 225, in handle
self.check_domain(domain, **options)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 198, in check_domain
self.store_dnsbl_result(domain, provider, results, **options)
File "/srv/modoboa/env/lib/python2.7/site-packages/modoboa/admin/management/commands/subcommands/_mx.py", line 107, in store_dnsbl_result
models.DNSBLResult.objects.bulk_create(to_create)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py", line 452, in bulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py", line 1062, in _batched_insert
inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/query.py", line 1045, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1054, in execute_sql
cursor.execute(sql, params)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/srv/modoboa/env/lib/python2.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
django.db.utils.IntegrityError: duplicate key value violates unique constraint "admin_dnsblresult_domain_id_9710ce0d_uniq"
DETAIL:  Key (domain_id, provider, mx_id)=(1, aspews.ext.sorbs.net, 55) already exists.```

# Fixed code
def store_dnsbl_result(self, domain, provider, results, **options):
    """Store DNSBL provider results for domain."""
    alerts = {}
    to_create = []
    for mx, result in list(results.items()):
        if not result:
            result = ""
        dnsbl_result = models.DNSBLResult.objects.filter(
            domain=domain, provider=provider, mx=mx
        ).first()
        trigger = False
        if dnsbl_result is None:
            to_create.append(
                models.DNSBLResult(
                    domain=domain, provider=provider, mx=mx, status=result
                )
            )
            if result:
                trigger = True
        else:
            dnsbl_result.status = result
            dnsbl_result.save()
            if not dnsbl_result.status and result:
                trigger = True
        if trigger:
            if domain not in alerts:
                alerts[domain] = []
            alerts[domain].append((provider, mx))
    models.DNSBLResult.objects.bulk_create(to_create)
    if not alerts:
        return
    emails = list(options["email"])
    if not options["skip_admin_emails"]:
        emails.extend(
            domain.admins.exclude(mailbox__isnull=True).values_list("email", flat=True)
        )
    if not len(emails):
        return
    with mail.get_connection() as connection:
        for domain, providers in list(alerts.items()):
            content = render_to_string(
                "admin/notifications/domain_in_dnsbl.html",
                {"domain": domain, "alerts": providers},
            )
            subject = _("[modoboa] DNSBL issue(s) for domain {}").format(domain.name)
            msg = EmailMessage(
                subject, content.strip(), self.sender, emails, connection=connection
            )
            msg.send()