Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

173
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda