diff options
author | 2022-02-22 00:05:35 +0100 | |
---|---|---|
committer | 2022-02-22 00:05:35 +0100 | |
commit | 173d3671793ecd0ed85aeef0441068070288ed9a (patch) | |
tree | 5026ef3788e33305fa995ea806d09ae0a57ea129 | |
parent | Merge pull request #666 from python-discord/integrityerror-duplicate-infracti... (diff) | |
parent | Assert we're dealing with the unique constraint (diff) |
Merge pull request #669 from python-discord/refine-constraint-check
Assert we're dealing with the unique constraint
-rw-r--r-- | pydis_site/apps/api/viewsets/bot/infraction.py | 24 |
1 files changed, 16 insertions, 8 deletions
diff --git a/pydis_site/apps/api/viewsets/bot/infraction.py b/pydis_site/apps/api/viewsets/bot/infraction.py index 31e8ba40..7e7adbca 100644 --- a/pydis_site/apps/api/viewsets/bot/infraction.py +++ b/pydis_site/apps/api/viewsets/bot/infraction.py @@ -281,11 +281,19 @@ class InfractionViewSet( """ try: return super().create(request, *args, **kwargs) - except IntegrityError: - raise ValidationError( - { - 'non_field_errors': [ - 'This user already has an active infraction of this type.', - ] - } - ) + except IntegrityError as err: + # We need to use `__cause__` here, as Django reraises the internal + # UniqueViolation emitted by psycopg2 (which contains the attribute + # that we actually need) + # + # _meta is documented and mainly named that way to prevent + # name clashes: https://docs.djangoproject.com/en/dev/ref/models/meta/ + if err.__cause__.diag.constraint_name == Infraction._meta.constraints[0].name: + raise ValidationError( + { + 'non_field_errors': [ + 'This user already has an active infraction of this type.', + ] + } + ) + raise # pragma: no cover - no other constraint to test with |