Rahul Sharma
Rahul Sharma

Reputation: 2495

Get model from multiple apps at once using apps.get_model

I am creating an API that can access multiple apps in a single project and get model from from all of these apps

for that I tried this:

def get(self, request, **kwargs):
    m = request.GET['model']
    depth = request.GET['depth']
    print("model")
    model = apps.get_model('masters', str(m))
    obj1 = model.objects.all()

It is working fine when I wanna import model from a single app but in my project I have multiple apps linked together and for this I tried:

    model = apps.get_model(['masters','dockets'], str(m))

but got an error TypeError: unhashable type: 'list'. apps.get_model doesn't take list but is there any workaround to this?

Upvotes: 1

Views: 171

Answers (1)

Sandil Ranasinghe
Sandil Ranasinghe

Reputation: 768

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.

Upvotes: 1

Related Questions