0

Suppose here is my models.py

models.py

from django.db import models
from django.contrib.auth.models import *

# Create your models here.

class A(models.Model):
    p = models.CharField(max_length=200)

class B(models.Model):
    d = models.OneToOneField(User)
    e = models.ForeignKey(A)

class C(models.Model):
    f = models.CharField(max_length=200)
    g = models.ForeignKey(A,related_name="c")

i wanto import these models inside my views like this.

from app import models
def import():
    list=['A','B','C']

    for x in list:
        from model import x

import()

Please suggest me a better solution ,I am new to python django.Thanks in advance.

edit

i want to use this loop for some reason.

vipin
  • 670
  • 2
  • 9
  • 25

3 Answers3

1

Better to just import the models file itself and reference them from there.

from my_app import models

models.A.objects.all()
models.B.objects.all()

Avoid from my_app import *: it can lead to confusion and namespace pollution, plus explicit is better than implicit.

But of course if you already know the list of models, you can simply import those directly:

from my_app.models import A, B, C
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

you can also do something like this answer suggested Dynamic module import in Python

import imp
import os

def load_from_file(file path, expected_class):
 class_inst = None


 mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])

 if file_ext.lower() == '.py':
     py_mod = imp.load_source(mod_name, filepath)

 elif file_ext.lower() == '.pyc':
     py_mod = imp.load_compiled(mod_name, filepath)

 if hasattr(py_mod, expected_class):
     class_inst = getattr(py_mod, expected_class)()

 return class_inst

i.e

 module = load_from_file(file_path, expected_class)
Community
  • 1
  • 1
user3684792
  • 2,542
  • 2
  • 18
  • 23
-1

My understanding is that you are trying to import all classes of models in your views file

simple way is:

from app.models import *
Avinash Garg
  • 1,374
  • 14
  • 18