# Dynamic raw query (select clause) Django

**URL:** <https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017>\
**Category:** ORM\
**Created:** [April 5, 2022, 3:08pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017 "2022-04-05T15:08:57Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 3:08pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/1 "2022-04-05T15:08:57Z")

</div>

I’m trying to execute a raw query in Django where I dynamically want to pick column names.  
Eg

```
   def func(all=True){
   if all:
      query_parameters = {
           'col': '*'
      }
   else:
      query_parameters = {
           'col': 'a,b,c'
      }
    with connections["redshift"].cursor() as cursor:
        cursor.execute(
            "select %(col)s from table limit 2 ;",
            query_parameters,
        )
        val = dictfetchall(cursor)
        return val
    }

```

Django is executing it like.

`select "*" from table limit 2;`

so the output is just like `select "*"`

`*`

and in the else case it is executed like

`select "a,b,c" from table limit 2;`

so the output is `a,b,c`

How can I run the command so that Django run it like

`select a , b , c from table limit 2`

so that the output is

```auto
a b c 
1 2 3 
4 5 6 

```

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 3:23pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/2 "2022-04-05T15:23:15Z")

</div>

would something like this work?

```auto
fields = ['a','b','c']
fields.append('d')
objects = Model.objects.only(*fields).filter()[:2]

```

---

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 3:39pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/3 "2022-04-05T15:39:27Z")

</div>

This is just a simple version of the actual problem. I cant use ORM for this particular issue, I have to use raw query. Is this not possible with raw query ?

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 3:41pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/4 "2022-04-05T15:41:05Z")

</div>

fair enough, how more complex is it?  
We can’t be right/wrong and/or give good/bad ideas if we do not have more details than you gave 🙂

---

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 3:44pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/5 "2022-04-05T15:44:54Z")

</div>

Actually, it’s a legacy system and the query contains 5-10+ strange combinations of joins. We surely will re-write everything in ORM at a later stage of the project. But for the initial presentation, we are reusing the queries.

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 3:49pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/6 "2022-04-05T15:49:53Z")

</div>

ah ok. Fair enough indeed.

Well what I proposed allows you to use the ORM, all the while dynamically building the list of fields/columns you want to fetch from the database:

```auto
fields = ['a','b','c']
fields.append('d')
field.insert(0, 'z')
limit = 2
objects = Model.objects.only(*fields).filter()[:limit]

```

this will result in something similar to the following query being generated and sent over the wire:

```auto
SELECT z, a , b , c, d FROM objects LIMIT 2;

```

---

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 3:55pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/7 "2022-04-05T15:55:20Z")

</div>

Thanks for this, I know the ORM way. Just wanted to know if it’s possible with raw query.

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 3:57pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/8 "2022-04-05T15:57:33Z")

</div>

heh 😉

> <https://stackoverflow.com/questions/71753438/dynamic-raw-query-select-clause-django>

---

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 3:59pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/9 "2022-04-05T15:59:32Z")

</div>

🤣 😅 Now I think its not possible with raw.

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 4:11pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/10 "2022-04-05T16:11:38Z")

</div>

have you tried something like this?

```auto
cols = ['a, b']
cursor.execute("SELECT %s FROM table", [','.join(cols)])

```

i.e. w/o the keywords syntax?

---

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 4:23pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/11 "2022-04-05T16:23:29Z")

</div>

Thanks, I tried but didn’t work out. But just after the last reply. I just got an idea and the hack worked. It’s working now.

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 4:25pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/12 "2022-04-05T16:25:06Z")

</div>

Well, tell us about the hack! 🙂

---

<div class="post-metadata">

**Author:** ![nikhilbadyal](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/nikhilbadyal/32/8035_2.png) [@nikhilbadyal](https://forum.djangoproject.com/u/nikhilbadyal)\
**Post date:** [April 5, 2022, 4:38pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/13 "2022-04-05T16:38:15Z")

</div>

Prepared query step by step

Input data (Columns I need)

_self.export\_col = “a,b,c”_

```auto
def calc_col(self):
        if self.exp == 'T':
            select_col = ""
            self.export_col = self.export_col.split(',')
            for col in self.export_col:
                select_col += col + ","
            select_col = select_col[:-1]
            self.export_col = select_col
        else:
            self.export_col += '*'

def prepare_query(self):
        query += " SELECT "
        query += self.export_col
        query += """ from table limit 2;"""

```

---

<div class="post-metadata">

**Author:** ![plopidou](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/plopidou/32/5148_2.png) [@plopidou](https://forum.djangoproject.com/u/plopidou)\
**Post date:** [April 5, 2022, 4:39pm UTC](https://forum.djangoproject.com/t/dynamic-raw-query-select-clause-django/13017/14 "2022-04-05T16:39:48Z")

</div>

I see… bet you can’t wait to migrate this to something newer! 🙂
