from django.apps import apps
# Step 1: Get the model class by name
def get_model_by_name(model_name):
try:
# Step 2: Get the app containing the model
app_label, model_class_name = model_name.split('.')
app_config = apps.get_app_config(app_label)
# Step 3: Get the model class from the app
model_class = app_config.get_model(model_class_name)
return model_class
except (ValueError, LookupError):
# Handle invalid model name or app not found
return None
# Example Usage:
# Step 4: Use the function to get the model class
model_name = 'myapp.MyModel'
my_model_class = get_model_by_name(model_name)
# Step 5: Check if the model class was successfully retrieved
if my_model_class:
# You can now use my_model_class to work with the Django model
instance = my_model_class.objects.first()
print(instance)
else:
print(f"Model with name '{model_name}' not found.")