Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8549003
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T13:37:35+00:00 2026-06-11T13:37:35+00:00

I have this code: try: principal = cls.objects.create( user_id=user.id, email=user.email, path=’something’ ) except IntegrityError:

  • 0

I have this code:

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

It tries to create a user with the given id and email, and if there already exists one – tries to get the existing record.

I know this is a bad construction and it will be refactored anyway. But my question is this:

How do i determine what kind of IntegrityError has happened: the one related to unique constraint violation (there is unique key on (user_id, email)) or the one related to not null constraint (path cannot be null)?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T13:37:36+00:00Added an answer on June 11, 2026 at 1:37 pm

    psycopg2 provides the SQLSTATE with the exception as the pgcode member, which gives you quite fine-grained error information to match on.

    python3
    >>> import psycopg2
    >>> conn = psycopg2.connect("dbname=regress")
    >>> curs = conn.cursor()
    >>> try:
    ...     curs.execute("INVALID;")
    ... except Exception as ex:
    ...     xx = ex
    >>> xx.pgcode
    '42601'
    

    See Appendix A: Error Codes in the PostgreSQL manual for code meanings. Note that you can match coarsely on the first two chars for broad categories. In this case I can see that SQLSTATE 42601 is syntax_error in the Syntax Error or Access Rule Violation category.

    The codes you want are:

    23505   unique_violation
    23502   not_null_violation
    

    so you could write:

    try:
        principal = cls.objects.create(
            user_id=user.id,
            email=user.email,
            path='something'
        )
    except IntegrityError as ex:
        if ex.pgcode == '23505':
            principal = cls.objects.get(
                user_id=user.id,
                email=user.email
            )
        else:
            raise
    

    That said, this is a bad way to do an upsert or merge. @pr0gg3d is presumably right in suggesting the right way to do it with Django; I don’t do Django so I can’t comment on that bit. For general info on upsert/merge see depesz’s article on the topic.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this code: try { using (FileStream fs = File.Create(path)) { } File.Delete(pathToStore);
I have this code: try: parent_comment = models.Comment.all_objects.get(id=parent_comment_id) except models.Comment.DoesNotExist: parent_comment = None if
I have this code: try { files = Directory::GetFiles(path); }catch(int){ MessageBox::Show(Error getting files.); return
I have this code try { //AN EXCEPTION IS GENERATED HERE!!! } catch {
I have this code: try { var _o, _l, i, _d = new Array(),
I have this snipped code: try{ JAXB.xmlJavaConverter(clientCommand); } catch (Exception e){ nServerFifo.add(clientCommand); } I
I have this code for update: public Boolean update() { try { data.put(ContactsContract.Groups.SHOULD_SYNC, true);
I have used this code to store Object to a file: try{ FileOutputStream saveFile=new
I have some code like this: try { doStuff(); } catch(SpecificException) { if(e.Message ==
When I have download sample code from this link and than try to build

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.