Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

174
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda