[Fixed]-Django: Check for related objects and whether it contains data

21👍

Use exists(). It’s designed to be used for exactly this type of situations:

for brand in Brand.objects.all():
    if not brand.cars_set.all().exists():
        # delete

Also it’s almost always faster than any other type of check because of the way it is designed to work at the database level. You can read details of exists() behaviour in the docs

10👍

From this question, for my code, this was faster:

for b in Brand.objects.filter(cars__isnull=True):
    # delete

If You have the ids (my case), I used this (60% faster than cars_set):

for brand_id in brand_id_set:
    if Brand.objects.filter(id=brand_id).filter(cars__isnull=True):
        # delete

I am using Django 1.11

2👍

I’d say the easiest way is like so:

# brand is an instance of Brand

if not brand.cars_set.all():
    # delete
else:
    # do something else

The Django docs cover foreign keys in quite a lot of detail.

1👍

cars_with_brands = Car.objects.filter(car_brand__isnull = False)
if cars_with_brands.count() == 0:
    # you can delete Brand Model
else:
   cars_with_brands.delete()
   # you can delete Brand Model

Leave a comment