[Answered ]-Get model from multiple apps at once using apps.get_model

1👍

As can be seen in the official documentations reference here https://docs.djangoproject.com/en/4.1/ref/applications/#django.apps.apps.get_model ,

apps.get_model(app_label, model_name, require_ready=True) method takes 3 arguments, where app_label and model_name are strings and require_ready is an optional boolean. Hence you get an error when you try to pass a list for the app_label argument.

If you only have 2 or 3 applications, a simple option for you would be to use a try except like this,

try:
    model = apps.get_model("masters", str(m))
except LookupError:
    model = apps.get_model("dockets", str(m))

However this is obviously not feasible if you are dealing with many applications.

Another alternative would be to alter your requests to contain both an app label and a model name.

def get(self, request, **kwargs):
    model_name = request.GET['model']
    app_label = request.GET['app_label'] # app label also as part of request
    depth = request.GET['depth']
    print("model_name")
    model = apps.get_model(str(app_label), str(m))
    obj1 = model.objects.all()

Otherwise, I suggest that you create a sort of registry with all the models from the different apps that may be accessed here, and in turn get the model from that registry.

Leave a comment