pythondatabasedjangoschemamodels

Dynamically generate import in Python, specifically for a Django model


Given a django Model, how could I auto-generate the valid import for it? I have a strictly internal function (only devs will use it) that takes a model and returns some information on it. The problem is, I don't know how to dynamically import stuff:

For example, my app structure could be:

-myproject
    --books
    --music

And the function:

def my_func(Model):
    from appname.models import Model
    ## Rest of function here ##

Is there a way I could auto-generate the import based on the model? I was thinking accessing _meta attributes to get the app_label but obviously, one needs the import to access Model._meta. Any thoughts would be appreciated.


Solution

  • I think get_model is what you need.

    from django.db.models.loading import get_model
    model = get_model('appname', 'ModelName')
    

    Now you can do this.

    objects = model.objects.all()