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
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.
The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.
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:
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With