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)
- [Django]-Invalid stdimage image path in admin
- [Django]-Django over https form redirection issues
- [Django]-Django + jQuery: Why CSRF verification fails on multiple simultaneous requests
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)
- [Django]-How do you use django-datatable-view
- [Django]-The proper Django way to make a form field required on CreateView, but optional on UpdateView?
Source:stackexchange.com