djangodjango-errors

django - checking to see if filter returns anything in the queryset


I'm a newb to Django. I need to check to see if a queryset returns any values at all, and if not, to skip to the next item in the loop. I tried try.. except ObjectDoesNotExist and that's not working. If a filter doesn't find anything, what does it return? How do I check for it?

Here's the existing code:

def assign_family_riders(leg):
    remaining_leg_riders = list(leg.riders.all())
    for car in CarAssignment.objects.filter(leg=leg):
        driver_family = car.driver.family
        try:
            riders = leg.riders.all().filter(family=driver_family)
        except ObjectDoesNotExist:
            continue
        for rider in riders:
            car.riders.add(rider)
            remaining_leg_riders.remove(rider)
    return remaining_leg_riders

Solution

  • You don't need to specifically check. If the filter doesn't return any objects, an EmptyQuerySet will be returned and the forloop will never be entered.

    riders = leg.riders.filter(family=driver_family)
    for rider in riders:
        ...
    

    If you really want to, you could simply do:

    riders = leg.riders.filter(family=driver_family)
    if riders:
        for rider in riders:
            ...
    

    The ObjectDoesNotExist exception is only raised when you are trying to retrieve a particular record using get():

    try:
         rider = leg.riders.get(...)
    except Rider.DoesNotExist:
        ...