[Solved]-Django ORM: See if a model has no foreign key entry in another model

16👍

Site.objects.filter(siteinfo__isnull=True)

0👍

There is a generic way to find the list of all reverse relations of a model.

reverse_model_array = [f.related_model for f in model._meta.get_fields() 
if f.auto_created and not f.concrete]

This will list all the models that have reference to this model(foreign key, many to many key, etc)

-4👍

I think this will working, but not so efficient:

with_no_site_info = [site for site in Site.objects.all() if site.site_infos_set.all().count() == 0]

👤MBarsi

Leave a comment