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




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)


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]


Leave a comment