Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Continue after Try has failed

I have a function:

def save_to_models(all_item_tags):
    from article.models import Articles    
    for item in all_item_tags:
        newobj = Articles()
        try:
            newobj.pub_date    =item.contents[9].contents[0]
        except:
            continue
        try:
            newobj.title       =item.contents[1].contents[0]
        except:
            continue    
        try:   
            newobj.description =item.contents[5].contents[0]
        except:
            continue
        try:
            newobj.image       =get_the_picture(item.contents[7])
        except:
            continue

        newobj.save()

each model has unique=True so I'm using try, except to skip over the error I get when its trying to input a data that's already in the database. How can I condense this code? I feel like its a lot of unnecessary lines of code.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Django is smart: like stated in one of the comments, it's only gonna raise an error when the save() method is called. Until then, Article is a normal Python object. What you should would look more like this :

from psycopg2 import IntegrityError # this is the actual error raised by psycopg2 (the postgres python driver)

from article.models import Articles

for item in all_item_tags:
    try:
        new_article = Articles(
            pub_date=item.contents[9].contents[0],        
            title=item.contents[1].contents[0],
            description=item.contents[5].contents[0],
            image=get_the_picture(item.contents[7])

        new_article.save() # this is where the actual save happens
    except IntegrityError:
        # Handle the exception here

Another (more advanced) option is to override the save() method and put your logic there.

That said, you could also use get_or_created to do that. It looks like this:

for item in all_item_tags:
    # this methods returns a boolean True of False if the object is already in the DB.
    # use your unique identifier here
    article, created = Article.objects.get_or_create(unique_id=...)

    # You can then do a classic if-else without handling any errors...
    if created: 
        # Great! The object a
    else:
        # the object exist, do something with it or not...

However, there are a few things I would suggest. My feeling is that you are diving into Django without really knowing Python. Django is a big beast that makes a lot of things really convenient (almost magical) but it's still Python. If you dive too deep and something breaks, it will be very hard for you to know what's going on. I would suggest furthering your knowledge of Python (it's an amazing language so it's gonna be fun) and then go back to Django or maybe start with a smaller framework like Flask which does less magic! For now, here's a link to the official doc on error handling so you can learn a bit more about it. Also, Django has really good doc so I would first look there if a problem arises.

Cheers and happy coding!

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!