[Django]-Accessing models by variable model name in django

5👍

You could do something like this:

getattr(models, model_name).objects.get(**my_dict)

It allows you to access the attributes of models via strings or variables.

3👍

You certainly can:

setattr(models, 'model_name', models.X)

This will set the model_name attribute to models.X (or models.Y), which will make your call models.model_name.objects.get(**my_dict) succeed.

Alternatively, you could save the model you want to use in a variable before doing your work and use that from then on:

model_name = models.X
model_name.objects.get(**my_dict)

0👍

Another way that I used is to use django.apps:

from django.apps import apps
model_name = 'X' # or 'Y'
my_dict = {"con":"something", "a":xy} # as suggested in the problem

model_class = apps.get_model(
  app_label='name_of_app_where_model_is_defined', 
  model_name=model_name
)
model_class.objects.get(**my_dict)

Leave a comment