1

I'm a beginner python user and am slighlty confused over the way modules are imported.

I've attached a screen shot to make it more clear what i'm asking.

I have the following code taken from djangoproject.com:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)

As the import statement refers to the folder named 'models' does this mean every module inside the 'models' folder is being imported into the session?

If so is models.Model a class found in one of those modules? If yes then why am i unable to find this class in any of the files? I've done a search for 'class Model(' in all of the files and can't find it.

enter image description here

Steve
  • 625
  • 2
  • 5
  • 17
  • 3
    It's in `base.py`: [`class Model(metaclass=ModelBase):`](https://github.com/django/django/blob/master/django/db/models/base.py) – sshashank124 Jan 06 '20 at 09:49
  • 2
    By importing a module you basically call the __init__ file of the module, if this includes the imports of the individual files then yes, but if it is empty then no. This is used to setup any module related code. https://pythontips.com/2013/07/28/what-is-__init__-py/ – John Dowling Jan 06 '20 at 09:50
  • 1
    Check this line `from django.db.models.base import DEFERRED, Model # isort:skip` in https://github.com/django/django/blob/master/django/db/models/__init__.py It's importing `Model` from `django.db.models.base`. – Mushif Ali Nawaz Jan 06 '20 at 09:51

1 Answers1

0

When you import a module like this, provided module.__init__.py is empty, nothing is getting imported.

If you can do something like:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)

then it means that CharField was either defined in __init__.py or somehow imported explicitly in module.__init__.py

So, to answer your question what was actually imported after you had called from django.db import models you need to check module.__init__.py

You can find more information here: What is __init__.py for? and here: https://docs.python.org/3/tutorial/modules.html

Alexander Pushkarev
  • 1,075
  • 6
  • 19