[Fixed]-How to import my django app's models from command-line?

28👍

You probably need to start a Shell first

python manage.py shell 

Then run your

from vc.models import *

5👍

python has a query system called ORM which are python queries based on MYSQL, we can apply these (queriyset) so they are called in django

go to the console and you must go to where your django project is and of course where the manage.py file is located and you will place the following ones:

python manage.py shell

you will notice that the shell will open there, we must import all our models that we want to perform queryset d as follows:

from APPS.models import Class

or

from .models import *
👤jpozzo

2👍

First method

Run in shell:

python manage.py shell

Then, in python console you can import your models:

from users.models import UserModel

Second method

Or from python console run these commands:

import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings")
django.setup()

# And then import models
from users.models import UserModel

my_app.settings is path to your settings.py

Third method

You can run manage.py shell from python console also. But in this case you should configure settings the same way as in the second method. This means second method is preferable, but in case you want to use django shell, you should use it like this:

# Run django shell
from django.core.management import execute_from_command_line
execute_from_command_line(['manage.py', 'shell'])

# Configure project
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings")
django.setup()

# And then import models
from users.models import UserModel
👤egvo

Leave a comment