0

Everything works fine until I delete all the objects and try to trigger the url, then it gives me this traceback: list index out of range. I can't use get because there might be more than one object and using [0] with filter leads me to this error when there's no object present, any way around this? I'm trying to get the recently created object of the Ticket model (if created that is) and then perform the logic, so that if the customer doesn't have any tickets, nothing happens but if the customer does then the logic happens

Models

class Ticket(models.Model):
    date_posted = models.DateField(auto_now_add=True, blank=True, null=True)
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)

Views

try:
    ticket = Ticket.objects.filter(customer=customer).order_by("-id")[0]
    now = datetime.now().date()
    set_date = ticket.date_posted
    check_time = now - set_date <= timedelta(hours=24)
    if check_time:
        print('working')
    else:
        print('not working')
except Ticket.DoesNotExist:
    ticket = None

context = {"check_time": check_time}
0

2 Answers 2

2

You can also do this:

ticket = Ticket.objects.filter(customer=customer).order_by("-id").first() or None
if ticket is not None:    
    now = datetime.now().date()
    set_date = ticket.date_posted
    check_time = now - set_date <= timedelta(hours=24)
    if check_time:
        print('working')
    else:
        print('not working')
    context = {"check_time": check_time}

instead of:

ticket = Ticket.objects.filter(customer=customer).order_by("-id")[0]
Sign up to request clarification or add additional context in comments.

2 Comments

but doing this would give me none type no attribute date_posted error, how would I fix that?
You need to check the value returned. if ticket is not None: do something...
1

Instead of this:

ticket = Ticket.objects.filter(customer=customer).order_by("-id")[0]

Use this using exists() which is a very efficient way if there is any object exist in DB:

tickets = Ticket.objects.filter(customer=customer).order_by("-id")
if tickets.exists():
   ticket = tickets.first()
else:
   ticket = None

Update

You can do the query inside the filter function.

tickets = Ticket.objects.filter(customer=customer, date_posted__lte=timezone.now().date() - timedelta(hours=24))

context = {"check_time": tickets.exists()}

3 Comments

now that check_time is gonna be inside of the if statement, how would I call it in context?
I have updated the answer. You can do this checking within the filter function
yh but I would still require the context tho, cuz I need to pass it to the template

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.