109

Looking through a Django tutorial I saw the following syntax:

from .models import Recipe, Ingredient, Instruction

Can someone explain how the .models works / what it does exactly? Usually I have:

from myapp.models import

How does it work without the myapp part in front of .models?

wobbily_col
  • 11,390
  • 12
  • 62
  • 86

2 Answers2

145

The . is a shortcut that tells it to search in the current package before the rest of the PYTHONPATH. So, if a same-named module Recipe exists somewhere else in your PYTHONPATH, it won't be loaded.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Sudeep Juvekar
  • 4,898
  • 3
  • 29
  • 35
  • 10
    @Hack-R - 2 dots represent parent directory. – Bhindi Feb 20 '17 at 06:59
  • @Bhindi oh thank you! I can't believe I didn't realize that – Hack-R Feb 20 '17 at 14:39
  • 10
    python checks for current directory first,so what is the use of . ? – ns15 Jul 21 '17 at 14:20
  • 8
    @shadow0359 the "current" directory is not always the directory in which the script resides. The script could be imported into another script in a different directory. – Aswin Jan 19 '18 at 00:08
  • 1
    These are called _relative imports_. See the full and official explanation here: https://www.python.org/dev/peps/pep-0328/#guido-s-decision, and the other answer here: https://stackoverflow.com/a/7279834/4561887. – Gabriel Staples Feb 10 '21 at 18:04
1

In addition of Sudeep Juvekar, this question is also related to manage.py's behavior.

In django-admin.py and manage.py:

It puts your project’s package on sys.path.

Zulu
  • 8,765
  • 9
  • 49
  • 56