leauradmin
leauradmin

Reputation: 385

ValueError: attempted relative import beyond top-level package when trying to import models from another app in django

I have two django applications in my project in my project named electron: the first api and the second elec_meter. The directories are organized as follows:

electron /
   api/
      views.py
      ...
   elec_meter/
      models.py
      ...

In the api / views.py file I want to import elec_meter / models.py.This is how I do it:

from ..elec_meter.models import *

But I get the following error message:

ValueError: attempted relative import beyond top-level package

or

from electron.elec_meter.models import *

In this case I receive this error message:

ModuleNotFoundError: No module named 'electron.elec_meter'

Here is a picture of my code

How can I solve this problem?

Upvotes: 2

Views: 1905

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477437

The Python root path is the electron directory, so you can not work with from electron.….

You can import the objects by importing it starting with the name of the app, not the project. This thus means that you import this with:

from elec_meter.models import Model1, Model2

while you can make wildcard imports, it is often considered an antipattern, since it is unclear what you import. This means that it can set references to point to objects exported by the elec_meter.models module, and thus override the original references.

Upvotes: 1

Related Questions