0

I am practicing using mysql in django and wanted to run a simply query on a database that I set up in my settings.py. I am connected to the database and can run the query fine in the manage.py shell. However, when I run the same code in a python file it does not work. Does anybody know why the query does not work in the python file?

query : 
from django.db import connections

def query(id):
    c = connections['default'].cursor()
    c.execute("SELECT * FROM `peptides_proteins_000005 WHERE protein_id=%s;",[id])
    rows = c.fetchone()
    return rows

print(query(4519))

In the shell I will get a row back with the information I want however, when run in the python file I get this error:

django.core.exceptions.ImproperlyConfigured: Requested setting DATABASES, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

Is there any way to run this command in views.py or another python file without using inspectdb to put my database in models?

1
  • Let me know if there is any other information you need Commented Jun 26, 2019 at 18:11

1 Answer 1

2

Well Django doesn't work that way. When you are executing the set of instructions using django shell it knows where to look for db because of settings.py file which is being loaded in the background by django.setup() which is responsible for populating the application registry. But when you are using it in general python shell it do not know anything about the settings.py file. It knows only about executing your current set of instructions. It do not loads the settings.py file.

Sign up to request clarification or add additional context in comments.

2 Comments

What can I do to run the query in a python file then? I want to query the database after the user has given me a id for the protein. Then I want to show this on a html page. Is there anyway to run this query in views.py? I would use models but my database is too big and I waited about and hour and it got 3 percent done. @Danish
You can use a form. Then extract the id with the request.GET.get('id') method at the backend and execute the same query. I think connection.cursor() will give you the same result so no need to use 'default'. pass the dict received via cursor.fetchone() to the frontend and extract result there or first print the result in terminal to understand what's coming and how to extract it in templates

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.