Search code examples
pythondjangocontent-typecode-reuse

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 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


Solution

  • 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.