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
- Adding forgot-password feature to Django admin site
- How can I schedule a Task to execute at a specific time using celery?
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.
- Python/Django: sending emails in the background
- How to clear all session variables without getting logged out
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
Source:stackexchange.com