pass a parameter into sql raw string and execute django

185 views
Skip to first unread message

Ronald Kamulegeya

unread,
Dec 19, 2020, 11:20:47 AM12/19/20
to Django users
I want to pass parameter in view and i execute the insert query as shown below.

I have searched and failed to get a solution.

Any hints.

Here is the code. My attempt is shown but not correct.

def post_payroll(request,p_id):
    p_id=2
    with connection.cursor() as cursor:
        query = "insert into payroll_payrolltemp(ndays,sdays,ot1hr,ot2hr,advance,bonus,penalty,post_status,worker_id,payperiod_id)"
        "select 0,0,0,0,0,0,0,0,sw.id,"
        str(p_id) +" as payperiod_id from staff_worker as sw"
        "where   sw.id in (select  w.worker_id from staff_workerpay as w where w .pay_frequency_id=1) order by sw.id"
        
        cursor.execute(query)

Julio Cojom

unread,
Dec 19, 2020, 9:32:26 PM12/19/20
to django...@googlegroups.com
Hello

First, create a query.py , just for order.

image.png

and declare a function with the parameters you want to receive.

Then, in your views.py 
image.png


you need to import connection from django.db 

finally , you can iterate over the rows fetched with one for loop.

image.png

You have to validate the input in your sql to avoid sql injection, the documentation tell something about it django documentation


regards.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/fe44ecbd-2555-4826-98e8-038212730a74n%40googlegroups.com.

Luciano Martins

unread,
Dec 20, 2020, 4:42:19 AM12/20/20
to Django users
Could you show your whole project?
Reply all
Reply to author
Forward
0 new messages