For my own use-case that had me stumble on this question, I was looking to see what app a model came from (for use with database router checks and whether to allow relationships, in case of different databases having the same model name).
For my case, it turns out that every model has a meta tag that indicates what app it came from. This may be helpful to others in the same situation.
For example, if a function is passed the model model
, the app that defined that model is found in model._meta.app_label
as a string. So for a database router, you could declare:
def allow_relation(self, obj1, obj2, **hints):
"""Determine whether to allow ForeignKey relationships between two objects"""
# if neither object is from MyApp, then this router doesn't care.
if 'MyApp' not in [obj1._meta.app_label, obj2._meta.app_label]:
return None # None means "no opinion" so other routers can still chime in
else:
# at least one object is from MyApp, so allow foreignkey relationships.
return True
get_app
andget_models
functions, rather than grepping the source code and hardcoding a list that needs to be maintained.