1
You could inspect all models to find out which ones have a foreign key on Group
and dynamically build the query. Use the model’s _meta
get_all_related_objects()
to get a list of RelatedObject
for your Group
model:
>>> related = Group._meta.get_all_related_objects()
>>> print related
[<RelatedObject: app:itemtypeone related to group>, <RelatedObject: app:itemtypetwo related to van>, <RelatedObject: app:itemtypethree related to group>]
Then build your lookups:
>>> excludes = dict(("%s__isnull" % ro.get_accessor_name(), False) for ro in related)
And execute your query:
>>> filtered = Group.objects.exclude(**excludes)
(warning: mostly untested code, might need some tweaking).
Source:stackexchange.com