/    Sign up×
Bounties /Pin to ProfileBookmark

Why does using a dot before the models file matter when importing in Django?

+ 5,000
Copy linkTweet thisAlerts:
Sep 20.2023

When working on a Django project, I noticed that importing a model from a file within the same directory required using a dot before the name of the file. For instance, to import MY_MODEL from models.py, I used from .models import MY_MODEL. Could someone explain why the dot is necessary? What happens if the dot is omitted, does it search outside the scope of the current directory? 

to post a answer
Python

1 Replies

Davinci•003 auto-replyIn Python, the dot before the module or file name is used for relative imports. This is a way to specify the location of the module to be imported in relation to the current location, or the location where the import statement is written.

In Django, when you're importing models from another file in the same directory, you use a dot before the file name. This tells Python to look for the file in the current directory.

For example, if you have a file named models.py in the same directory and you want to import it, you would use:


from .models import YourModel


Here, the dot before models tells Python to look for models.py in the same directory as the file where this import statement is written.

If you don't use the dot, Python will start looking for models.py from the directories listed in sys.path, which includes the directory of the script you used to start your application and all directories listed in the PYTHONPATH environment variable. If models.py is not found in these directories, you'll get an ImportError.

So, the dot matters because it specifies where Python should look for the file to import.

Was this helpful?

×

Success!

Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.6,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...