Importing Model Class into another app - Django - python

I am trying to import a model class from another app. My structure looks like the following:
mysite/
-- main/
models.py
-- webshop/
models.py
I'd like to import a model class from my webshop app into the main/models.py. I run the following in my main/models.py file:
from django.db import models
from ..webshop.models import Item
# Create your models here.
class Test(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
In my text editor everything seems fine. It finds the appropriate app and finds the model class Item which I need to import there.
When I run makemigrations I am getting the following error:
ValueError: attempted relative import beyond top-level package
I've read some other questions on SO on how to make this work but can't figure it out. Tried:
mysite.webshop.models import Item
aswell. But then I get a: ModuleNotFoundError: No module named 'mysite.webshop'.
Does anyone have suggestions?

From the error ValueError: attempted relative import beyond top-level package, I'm going to assume in your text editor, your current working directory is mysite/. And so using ..webshop.models you're trying to go up two directories above mysite/ which is why you're getting the error.
What you need to do is:
from django.db import models
from webshop.models import Item

Related

Unable to call a class using Django

If I do that :
from myapp import models
User.objects.first()
I got that error :
NameError : name 'User' is not defined
whereas if I do that
import myapp
myapp.models.User.objects.first()
it works
I don't understand at all why I have that problem
Thank you very much for your help !
Replace:
from myapp import models
with the following:
This way, you are telling Django which model classes to import rather than leaving Django guessing what to do with it.
It prevents you from loading unnecessary models which might not be used right away and could potentially increase load time.
from myapp.models import User
In your example, your have not imported class User actually. You have imported it's module called models
You can do one of these:
from myapp import models
models.User.objects.first()
Or:
from myapp.models import User
User.objects.first()

AttributeError: module 'django.db.models' has no attribute 'Models'

When I'm trying to migrate a new app onto the server i get this error
AttributeError: module 'django.db.models' has no attribute 'Models'- in terminal
I'm using PyCharm. I am very fresh to Django and web development so any tips will help. Thanks!
from django.db import models
# Create your models here.
class product(models.Model):
item = models.Textfiels()
description = models.Textfields()
price = models.Textfields()
There's no such class django.db.models.TextFields but this works for me on any recent version :
from django.db import models
class product(models.Model):
item = models.TextFiel()
description = models.TextField()
price = models.TextField()
You made 2 typos : the correct name is TextField and you typed Textfields (Python is case sensitive)
I suspect you didn't setup correctly your project under PyCharm. When correctly setup, it shows warnings on misspelled names (names underlined with red dots with default setting).
There's another variation to this question and that is in the form of:
AttributeError: module 'django.contrib.auth' has no attribute 'models'
As far as I can tell this is typically caused by conflicting imports or improperly imported files. Another cause could be changes to Django's updates but I'm not sure about that as I didn't find any documentation that changed that aspect of the Django library.
Short term solution to this is as follows:
from django.contrib.auth import models
class MyClass(models.User): """ """
This will allow you to at least test your runserver command and website on a browser of your choosing.
I'm still trying to figure out any other solutions to this problem that can be a fix for individually importing the 'auth' module itself.
At the time of this writing I'm using Django 2.2.6 whereas Django 2.2.7 is out and 2.2.8 is on the way to be released.
I'm not sure if this is the solution , but when I had this problem it was because in my admin.py file I had
from django.contrib import admin
from meetings.models import Meeting, Room
admin.site.register(Meeting, Room)
But changing it to solved the issue
from django.contrib import admin
# Register your models here.
from meetings.models import Meeting, Room
admin.site.register(Meeting)
admin.site.register(Room)

Django: Getting models with apps.get_model on models.py

On circular import of Django Is their any way i can grab a model object with myModel = apps.get_model('app_name', 'model_name') inside models.py file ?
I know i can use models.ForeignKey('app.model',....)
But in my case i am making a query in the models.py for custom function. So that i need to grab the model object. Also can't import it in normal way as already imported this file class in the other file. So must be a circular import.
This code myModel = apps.get_model('app_name', 'model_name') works fine on views.py but in models.py doesn't. Since according to django the all models.py get called after settings.py and after that views and others. so while trying to use get_model inside models.py getting this error
File "/home/mypc/.virtualenvs/VSkillza/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready
raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.
Thanks in advance :)
You can break the circular import by moving the import inside the custom function. That way, the model is loaded when the function runs, not when the module is loaded.
def my_function():
from myapp.models import MyModel
The circular import suggests that your code is structured incorrectly, but we can't give you any suggestions since you haven't shown it.
You can try this.
import importlib
mymodels = importlib.import_module("app.models")
mymodels.YourModel
#query
mymodels.YourModel.objects.all()

Django Rest: ImportError: cannot import name "model name"

In Django Rest, am getting the following error. Could any one trace whats the mistake I was done
My APP structure
test_APP
abc_APP
In abc_APP models.py I am trying to access Test model, but I am getting the following error. may be due to reverse loop ? if yes, how to fix ?
abc_APP # models.py
from test_APP.models import Test
ImportError: cannot import name Test

Python, Flask, SQLAlchemy: cannot import from models

I've got a weird problem.
I am building a Flask app with SQLAlchemy. I have a file with models, namely, models.py. And I have a User model there.
If I open my "views.py" and insert a string
import models
and then use the User model like
u=models.User.query.filter_by(name='John',password='Doe').first()
everything works fine.
But if instead of "import models" i put
from models import User
Python crashes and says:
ImportError: cannot import name User
how can this be possible?
you most likely have a circular import; your, lets say 'app' module:
# app.py
import models
...
def doSomething():
models.User....
but your models module also imports app
import app
class User:
...
since models imports app, and app imports models, python has not finished importing models at the point app tries to import models.User; the User class has not been defined (yet). Either break the cyclic import (make sure models doesn't import anything that also imports models), or you'll just have to make do with models.User instead of the shorter User in app.
Instead of
from models import User
use
from models import *
In this case, you are importing the models into views.py therefore if you need a class from models, import it from views.py and the circular import problem will be resolved.

Categories