# Query sql in views.py

**URL:** <https://forum.djangoproject.com/t/query-sql-in-views-py/19215>\
**Category:** Using the ORM\
**Created:** [March 2, 2023, 11:46am UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215 "2023-03-02T11:46:19Z")\
**Posts on this page:** 15\
**Page:** 1

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 2, 2023, 11:46am UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/1 "2023-03-02T11:46:19Z")

</div>

I have the following database structure in settings.py

```auto
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    },
    'users_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'users',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '3306' 
    },
    'intranet_db': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'intranet',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '3306' 
    },
     'nav_db': {
        'ENGINE': 'django.db.backends.postgresql',
        'OPTIONS': {
            'service': 'my_service',
            'passfile': '.my_pgpass',
        },
    }
}

```

I simply want the last database called nav\_db to query data.

How could I indicate the table / field to the query?

What I think is correct is

`query.objects.using('nav_db').all()`

But I don’t know how to tell it to make a query as such sql…

select name from customers

Thank you.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 2, 2023, 1:27pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/2 "2023-03-02T13:27:45Z")

</div>

Note that in:

> [@peya02](#):
>
> query.objects.using(‘nav\_db’).all()

That `query` at the beginning is the name of the Model on which you’re writing your query.

> [@peya02](#):
>
> But I don’t know how to tell it to make a query as such sql…

The same way that you would write any other query in Django. The only change here is to add the `using` method to the queryset.

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 2, 2023, 1:45pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/3 "2023-03-02T13:45:35Z")

</div>

I don’t understand your phrase very well, I don’t have a model for this database since it will only be for queries.  
So how can I?

This is not correct because I don’t have a model called query, right?

`query.objects.using('nav_db').all()`

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 2, 2023, 2:00pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/4 "2023-03-02T14:00:13Z")

</div>

> [@peya02](#):
>
> I don’t have a model for this database since it will only be for queries.

You can still create models to allow you to write queries using the ORM. (That’s something we do frequently here.)

Otherwise, see [Performing raw SQL queries | Django documentation | Django](https://docs.djangoproject.com/en/4.1/topics/db/sql/#executing-custom-sql-directly)

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 3, 2023, 9:27am UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/5 "2023-03-03T09:27:10Z")

</div>

Hello,

After reading I have understood the following, I can do the query as follows, and using a specific connection (sql)

```auto
def NoConformidad(request):
    with connections['nav_db'].cursor() as cursor:
        cursor.execute("SELECT Name FROM Customer")
        row = cursor.fetchone()
    return row

```

But I get the following error:

 ![image](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/2/210b1bbf1ee49d5e105455fb555cf7429c360ae9.png)

does this have to do with my sql server where i query?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 3, 2023, 12:12pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/6 "2023-03-03T12:12:36Z")

</div>

Possibly? I don’t recognize that port number (7048).

The error is being thrown in the psycopg2 module, so it’s one of the databases you’ve got defined as a PostgreSQL server. The full traceback would help identify which line caused the error.

Note: Please don’t paste an image of a traceback. Copy/paste the traceback from the console log.

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 3, 2023, 12:31pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/7 "2023-03-03T12:31:54Z")

</div>

Sorry, I think the problem already starts with the wrong connection.

Can you confirm that the connection to a sql database is correct?

Now I have this configuration

```auto
'nav_db': {
        'ENGINE': 'django.db.backends.postgresql',
        'HOST': 'locahost',
        'PORT': '',
        'NAME': 'PRUEBA',
        'USER': 'test',
        'PASSWORD': ''        
    },

```

The truth is that I have seen several options and none of them suit me…

In the ENGINE section I am not very clear what to put.

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 3, 2023, 12:37pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/8 "2023-03-03T12:37:41Z")

</div>

There’s no one-size-fits-all answer here.

I can’t tell you what you should put without knowing what database you’re trying to connect to, what server it’s running on, and what type of database it is.

Review the docs at [Settings | Django documentation | Django](https://docs.djangoproject.com/en/4.1/ref/settings/#databases) and [Databases | Django documentation | Django](https://docs.djangoproject.com/en/4.1/ref/databases/)

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 3, 2023, 12:45pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/9 "2023-03-03T12:45:04Z")

</div>

Do not really understand.  
The real server is windows server 2012 although I can test with windows 10 and the database is sql

From what it puts in the documentation, it would not be any of these

The database backend to use. The built-in database backends are:

- `'django.db.backends.postgresql'`
- `'django.db.backends.mysql'`
- `'django.db.backends.sqlite3'`
- `'django.db.backends.oracle'`

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 3, 2023, 12:46pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/10 "2023-03-03T12:46:22Z")

</div>

> [@peya02](#):
>
> database is sql

Are you saying that the database is Microsoft’s SQL server?

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 3, 2023, 12:49pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/11 "2023-03-03T12:49:39Z")

</div>

> [@KenWhitesell](#):
>
> Are you saying that the database is Microsoft’s SQL server?

Yes correct, it is from microsoft sql

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [March 3, 2023, 12:54pm UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/12 "2023-03-03T12:54:09Z")

</div>

See the docs at [Using a 3rd party database backend](https://docs.djangoproject.com/en/4.1/ref/databases/#using-a-3rd-party-database-backend)

You will need to use [mssql-django · PyPI](https://pypi.org/project/mssql-django/)

Side note, in the future, you will want to refer to your database as “SQL Server” or “MS SQL Server”, not just as “sql”. The acronym “sql” is a generic term that applies to a number of different things.

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 8, 2023, 6:48am UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/13 "2023-03-08T06:48:22Z")

</div>

Ok, now I think that it is already correctly connected to SQL Server but I don’t know how to check it since the query tells me the following.

```auto
Internal Server Error: /noConformidad/
Traceback (most recent call last):
  File "C:\Users\apenaranda\Desktop\Python_Intranet\env\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\apenaranda\Desktop\Python_Intranet\env\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\apenaranda\Desktop\Python_Intranet\reclamaciones\views.py", line 151, in NoConformidad
    cursor.execute("SELECT Golmar$Customer.Name FROM Golmar$Customer WHERE Golmar$Customer.Name = 'DISTRIBUIDORES-7' ", [self.Name])
                                                                                                                          ^^^^^^^^^
AttributeError: 'WSGIRequest' object has no attribute 'Name'

```

Query in views.py

```auto
def NoConformidad(self):
    with connections['nav_db'].cursor() as cursor:
        cursor.execute("SELECT Name FROM Golmar$Customer WHERE Name = DISTRIBUIDORES-7", [self.Name])
        row = cursor.fetchone()
    return row

```

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 8, 2023, 8:41am UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/14 "2023-03-08T08:41:22Z")

</div>

Well I already managed to get the information with

```auto
with connections['nav_db'].cursor() as cursor:
        cursor.execute("SELECT * FROM Golmar$Customer WHERE Name = 'DISTRIBUIDORES-7';") # Here

        for row in cursor.fetchall(): # Here
            print(row)

        print(cursor.fetchall()) # []

    return HttpResponse("NoConformidad")

```

What if I want to show it on the page and not on the console?

---

<div class="post-metadata">

**Author:** ![peya02](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/peya02/32/11900_2.png) [@peya02](https://forum.djangoproject.com/u/peya02)\
**Post date:** [March 8, 2023, 10:11am UTC](https://forum.djangoproject.com/t/query-sql-in-views-py/19215/15 "2023-03-08T10:11:30Z")

</div>

I already got it. Many thanks for everything.
