0

I'm creating a simple script used to generate fixture data for a given django model. I cannot figure out how to create an import statement which accepts user input, to allow me to perform the actual logic on the selected model.

I've tried various combinations of imp, importlib.util.spec_from_file_location, importlib.import_module, __import__, Create an import statement using variable "interpolation"

The closest I've gotten is:

def import_function(app, model):
    exec(f"from {app}.models import {model}")
    exec(f"print({model}.objects.all())") #This works.
import_function("home", "Person")

My thinking is: I create a module called 'fixture.py'. Within that module is a custom import function. I import the module into the environment created by python manage.py shell so as to obviate the need for modifying the PATH. Then, I call the function using fixture.import_function(app, model).

I've managed to generate the fixture data this way, but only when I'm hardcoding the import statement, i.e. from home.models import Person. #fixture generating logic.

PersonPr7
  • 136
  • 7

1 Answers1

0

This is the wrong approach. There's no need to fiddle with imports or construct names dynamically. Use the functions that Django provides to find the model:

from django.apps import apps
model = apps.get_model(app, model)
print(model.objects.all())
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895