0

I am writing a website that requires importing different sql models to different urls according to argument. Specifically:

if the url is:

http://127.0.0.1:8000/detail/abc

where abc is the also a model name in sql database

then in views.py:

def detail(request, arg):
  from book.models import arg

my expected result is:

  from book.models import abc

any idea? thanks a lot.

CL. L
  • 237
  • 1
  • 7
  • 22

3 Answers3

0

you can dynamically import like this :

request = "test.com/t/winsound"
importValue = request.rsplit("/",1)[1]
exec("import "+importValue)
winsound.Beep(600,600)
ClumsyPuffin
  • 3,909
  • 1
  • 17
  • 17
  • Thanks for the prompt reply. I try to embed that in the code, but it results in ImportError Exception Value: cannot import name 'abc'. – CL. L Dec 26 '16 at 13:42
  • Actually, I search a bit and found that something like get_models application can help, but cannot figure out how to use it in Django 1.10.4. Do you have any idea? – CL. L Dec 26 '16 at 13:43
0

You can use getattr()

In your case:

def detail(request, arg):
    import books.models as books_models
    function = getattr(books_models, arg)

Another way of doing it is like this:

function = getattr(__import__('books.models'), arg)

wencakisa
  • 5,850
  • 2
  • 15
  • 36
  • I think this will be helpful too: http://stackoverflow.com/questions/4075190/what-is-getattr-exactly-and-how-do-i-use-it – wencakisa Dec 26 '16 at 13:55
0

Thanks all for the inputs. While your answers should be valid, I also figure out a way to it as below:

from django.apps import apps

def detail(request, arg):
    db_arg = apps.get_model('book', arg)

then the abc database will be assigned to db_arg

I think this question is duplicate to this one: What is the equivalent of django.db.models.loading.get_model() in Django 1.9?

Community
  • 1
  • 1
CL. L
  • 237
  • 1
  • 7
  • 22