django - checking to see if filter returns anything in the queryset
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:
...
As Timmy said in his answer, your loop will not be entered if the queryset returns nothing. On the other hand, if you really want to know the number of records a filter will return, you can call its count()
method: CarAssignment.objects.filter(leg=leg).count()
This performs a SELECT COUNT(*)
for you in the background without retrieving any records.
See here for more information.