Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 774
mb52089 Avatar asked Apr 30 '12 01:04

mb52089


People also ask

Can I filter a QuerySet Django?

With the Django QuerySet class, you can apply filters that return QuerySets defined by your filters. The filter() method returns all objects that match the keyword arguments given to the method.

What filter returns in Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.


1 Answers

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:
    ...
like image 88
Timmy O'Mahony Avatar answered Oct 12 '22 10:10

Timmy O'Mahony