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


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


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


I’d say the easiest way is like so:

# brand is an instance of Brand

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

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


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

Leave a comment