Red Cricket
Red Cricket

Reputation: 10470

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

I would like to be able to manipulate my Django app's models via the python console. I am able to do this with PyCharm but I do not have access to PyCharm in this scenario. I tried this:

[root@myhost scripts]# source /apps/capman/env/bin/activate
(env) [root@myhost scripts]# python
Python 2.7.14 (default, Jan  9 2018, 20:51:20)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> from vc.models import *

But I get the error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named vc.models 

What am I doing wrong?

Upvotes: 20

Views: 25205

Answers (3)

egvo
egvo

Reputation: 1865

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

Upvotes: 4

jpozzo
jpozzo

Reputation: 141

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 *

Upvotes: 5

dfundako
dfundako

Reputation: 8314

You probably need to start a Shell first

python manage.py shell 

Then run your

from vc.models import *

Upvotes: 29

Related Questions