views:

25

answers:

2

I want to make some functions that are re-usable by any model so that I can specify the appname and model in string format and then use this to import that model and make calls to it such as creating database fields, updating, deleting, etc...

I had thought I could do this using contenttypes in Django but am trying this, as below and am getting the error message "'ContentType' object is not callable":

    from django.contrib.contenttypes.models import ContentType
    instancemodelname = ContentType.objects.get(app_label="myappname", model="mymodelname")

    b = instancemodelname(account_username='testtestest')
    b.save()
    >>>>'ContentType' object is not callable

I would appreciate any advice on the proper way to do this, thanks

+2  A: 

The following code will work:

instancemodelname = ContentType.objects.get(app_label="myappname", model="mymodelname")
b = instancemodelname.model_class()(account_username='testtestest')
b.save()

That said I am not entirely convinced that contenttypes is the best way to achieve what you want.

Manoj Govindan
thanks, I'm not sure it is the best way either... I would appreciate tips on any other methods as this would be useful as well for a context outside of Django in the future
Rick
your answer is spot on so I've already chosen it as correct, however would be interested as to alternate ways to do this so that I can look into it further to better improve my knowledge of this sort of thing
Rick
One way to go about this would be to write a function(s) to import the model at runtime and then create instances etc. Save the function in an utility suite.
Manoj Govindan
+1  A: 

Don't use the ContentType model. There's a function for exactly this use case that doesn't genereate a database hit:

from django.db.models import get_model
mymodel = get_model("myappname", "mymodelname")
b = mymodel(account_username='testtestest')
b.save()
piquadrat