dev9
dev9

Reputation: 2382

How to unambiguously identify a Model as a lowercase string in Django

I want to pass a model name as an URL parameter, so I can use it to access a specified model class in my view. For example:

/app_label/model_name

and in views.py:

from django.db.models.loading import get_model
model = get_model(app_label, model_name)

The problem is - I want my url to be case-insensitive. Therefore, I cannot just use the code above, because one of the models can look like these below:

MyModel, MySuperModel, MyAwesomeSuperModel

Is there any way to identify a Model unambiguously as a lowercase string?

I thought about using table_name however it would mean looping over every model in the project each time a request is processed. Not very efficient.

Upvotes: 1

Views: 804

Answers (2)

doniyor
doniyor

Reputation: 37894

your_model_object.__class__.__name__.lower()

gives you the lower case name of model name if it can help you

Upvotes: 0

catavaran
catavaran

Reputation: 45575

I am afraid you will have to iterate over app's models list but you can cache it:

from django.core.exceptions import ImproperlyConfigured
from django.db.models import get_app, get_models

APPS_MODELS = {}

def get_model(app_name, model_name):

    app_models = APPS_MODELS.get(app_name)
    if app_models:
        return app_models.get(model_name)

    try:
        app = get_app(app_name)
    except ImproperlyConfigured: # no such app
        return None

    APPS_MODELS[app_name] = dict((model._meta.model_name, model)
                                     for model in get_models(app))

    return APPS_MODELS[app_name].get(model_name)

Upvotes: 1

Related Questions