B
B
bituke2021-09-08 15:42:16
Python
bituke, 2021-09-08 15:42:16

How to continue the loop until the error is gone?

I need the code to look like this:

try:
      ticker_value_at_start_date = TickerValue.objects.get(date=date, ticker=ticker)
    except TickerValue.DoesNotExist:
      try:
        date = date - timedelta(1)
        ticker_value_at_start_date = TickerValue.objects.get(date=date, ticker=ticker)
      except TickerValue.DoesNotExist:
        try: 
          date = date - timedelta(2)
          ticker_value_at_start_date = TickerValue.objects.get(date=date, ticker=ticker)
        except:
          date = date - timedelta(3)
          ticker_value_at_start_date = TickerValue.objects.get(date=date, ticker=ticker)

but like this :
count = 1
While not TickerValue.DoesNotExist:
  date = date - timedelta(count)
  ticker_value_at_start_date = TickerValue.objects.get(date=date, ticker=ticker)

How to implement such a cycle?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-09-08
@bituke

Use try-else to track the success of the call and break to exit the loop.

for d in range(0, 10): # сколько отступов делать
    try:
        #к слову, так у тебя date будет считаться не -1, -2, -3... а -1, -3, -6...
        date = date - timedelta(d) 
        pass # операция, которую ты хочешь выполнить
    except TickerValue.DoesNotExist: #отработает при  ошибке
        pass #или time.sleep(), чтобы подождать перед следующим вызовом - если надо
    else: #отработает при успешном выполнении блока try
        break #выходим из for

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question