-1

What i want is to make a string var callable. I just have a list with different models_names and i want to call their create methods like this way.

class Object_model_a:
     #def ...
class Object_model_b:
     #def ...
class Object_model_c:
     #def ...

list = ('Object_model_a', 'Object_model_b', 'Object_model_c')
x = list[0]() # this must create a new instance of Object_model_a

This is possible to develop using php like this way:

$hi = 'Hello'
$Hello = 'Hi!!'
echo $$hi
>> Hi!!

Anyone knows if this is possible using django?? This will simplify a lot my code.

Thanks a lot!

jsujar
  • 1
  • 1
    No, that won't simplify your code. Use [Factory](http://en.wikipedia.org/wiki/Factory_method_pattern) instead. – DrTyrsa May 29 '12 at 11:46
  • 1
    "What i want is to make a string var callable" No, you don't. – Marcin May 29 '12 at 11:49
  • What keeps you from storing the classes in the list? e.g. [Object_model_a,Object_model_b] etc. – devsnd May 29 '12 at 12:00
  • The reason which i have to do this is because i'll never know the type of the model that this script will manage, and on future develop this will be able to get information about any other model. – jsujar May 30 '12 at 07:44

3 Answers3

4

You could use Django's get_model helper function, which takes the app name and model name and returns the model class.

from django.db.models import get_model

list = ('Object_model_a', 'Object_model_b', 'Object_model_c')
model = get_model('my_app_name', list[0]) # returns Object_model_a class
instance = model() # creates a model instance
Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

If for whatever reason you have a string that represents a particular class, the correct way to use that to instantiate an object of that class is to place your classes in a dict, keyed by the strings, then just invoke the class.

classes = dict((c.__name__, c) for c in (Object_model_a, Object_model_b, Object_model_c))

instance = classes['Object_model_a']()

Obviously, you don't need to use the classname as the key.

Marcin
  • 48,559
  • 18
  • 128
  • 201
-1

Thanks for all your comments, this is the way i've solved this requirement.

def create_object_instance(model_name, id=None):
    for model in get_models():
        if str(model.__name__).lower() == str(model_name).lower():
            if id:
                try:
                    return model.objects.get(id=id)              
                except ObjectsDoesNotExist:
                    return None
            else:
                return model.objects.all()
    return None
jsujar
  • 1
  • 1
    This is kind of terrible. If you want to allow an arbitrary model to be specified, why not use `get_model`? – Marcin May 30 '12 at 08:14