Django - checking that a filter returns something in a query set

I am new to django. I need to check if the query returns the value of any values, and if not, then go to the next element of the loop. I tried to try other than ObjectDoesNotExist and this does not work. If the filter does not find anything, what does it return? How can I check 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
+3
source share
3 answers

You do not need to specifically check. If the filter does not return any objects, an EmptyQuerySet is returned, and forloop will never be entered.

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

If you really want this, you can simply do:

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

An exception ObjectDoesNotExistoccurs only when you try to get a specific record using get():

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

, , . , , , count(): CarAssignment.objects.filter(leg=leg).count()   SELECT COUNT(*) - .

. .

+2

I'm sure queryset returns nothing. You can probably check it with ./manage.py shell, and then see what is in riders.

0
source

All Articles