You probably want **
keyword pass-through:
def IsAvailable(model, attr, val):
obj = getattr(models, model)
res = obj.objects.get(**{attr: val})
return res
This passes the dictionary {attr: val}
as keyword arguments to get()
, i.e. {'foo': 'bar'}
calls get(foo='bar'}
.
Bonus points for making this generic:
def IsAvailable(model, **kwargs):
obj = getattr(models, model)
res = obj.objects.get(**kwargs)
return res
This lets you call IsAvailable(model, attr1=val1, attr2=val2)
, testing the availabilty of all attributes which might even be more convenient.
In Django 1.7 you can also resolve the model by name for the whole project across applications (also possible in django < 1.7, but using a different method).
from django.apps import apps
def get_model_dotted(dotted_model_name):
app_label, model_name = dotted_model_name.split(".", 1)
return apps.get_model(app_label, model_name)
def IsAvailable(model, **kwargs):
model = get_model_dotted(model_name)
res = model.objects.get(**kwargs)
return res;
Use as IsAvailable('app1.model1', attr1=value1)
.
Remember that get()
raises MultipleObjectsReturned
when more than one object matches the filter, so you might actually want
res = model.objects.filter(**kwargs)
or even only
return model.objects.filter(**kwargs).exists()