Django / Python, Make database save function re-usable (so that it takes modelname and appname from strings), using contenttypes or some other method?
I want to make some functions that are re-usable by any model so that I can specify the appname开发者_JS百科 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
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.
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()
精彩评论