IntegrityError: distinguish between unique constraint and not null violations

前端 未结 3 1830
误落风尘
误落风尘 2020-12-06 10:19

I have this code:

try:
    principal = cls.objects.create(
        user_id=user.id,
        email=user.email,
        path=\'something\'
    )
except Integri         


        
3条回答
  •  余生分开走
    2020-12-06 10:46

    Update as of 9-6-2017:

    A pretty elegant way to do this is to try/except IntegrityError as exc, and then use some useful attributes on exc.__cause__ and exc.__cause__.diag (a diagnostic class that gives you some other super relevant information on the error at hand - you can explore it yourself with dir(exc.__cause__.diag)).

    The first one you can use was described above. To make your code more future proof you can reference the psycopg2 codes directly, and you can even check the constraint that was violated using the diagnostic class I mentioned above:

    except IntegrityError as exc:
        from psycopg2 import errorcodes as pg_errorcodes
        assert exc.__cause__.pgcode == pg_errorcodes.UNIQUE_VIOLATION
        assert exc.__cause__.diag.constraint_name == 'tablename_colA_colB_unique_constraint'
    

    edit for clarification: I have to use the __cause__ accessor because I'm using Django, so to get to the psycopg2 IntegrityError class I have to call exc.__cause__

提交回复
热议问题