Django raw SQL queries


๐Ÿ’ก django์—์„œ SQL๋ฌธ์œผ๋กœ ๊ฐœ๋ฐœํ•˜๊ธฐ

์˜ค๋Š˜ django document๋ฅผ ์ฝ๋Š”๋ฐ ์šฐ์—ฐํžˆ ๋ฐœ๊ฒฌํ•˜๊ฒŒ ๋๋‹ค.

Django์—๋Š” raw() manager๊ฐ€ ์žˆ๋‹ค. ์ด ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ง์ ‘ ์ฟผ๋ฆฌ๋ฌธ์„ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

์ง์ ‘ ์‹ค์Šต์„ ์œ„ํ•ด์„œ djagno shell_plus์— ์ง„์ž…ํ–ˆ๋‹ค.


์ฟผ๋ฆฌ๋ฌธ ๋‚ด์—์„œ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ๋„˜๊ฒจ์ค„ ๋•Œ๋Š” ๋‘ ๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค.

โ’ˆ %s

์ฟผ๋ฆฌ๋ฌธ ์ž‘์„ฑ์‹œ WHERE ์ ˆ์— ๋“ค์–ด๊ฐˆ ๊ฐ’์„ ๋ฆฌ์ŠคํŠธ์— ๋„ฃ์–ด์„œ ๋„˜๊ฒจ์ค€๋‹ค.


โ’‰ %(key)s

๋‘ ๋ฒˆ์งธ ๋ฐฉ๋ฒ•์€ dict(ํ‚ค:๊ฐ’) ํ˜•ํƒœ๋กœ ๊ฐ’์„ ๋„˜๊ฒจ์ฃผ๋Š” ๋ฐฉ๋ฒ•์ด๋‹ค.


ํ•„๋“œ์˜ ์ด๋ฆ„์„ ๋‹ค๋ฅธ ์ด๋ฆ„์œผ๋กœ ๋ถˆ๋Ÿฌ์•ผ ํ•  ๊ฒฝ์šฐ ์•„๋ž˜์™€ ๊ฐ™์ด ์ž‘์„ฑํ•œ๋‹ค๊ณ  ํ•œ๋‹ค.

# CASE1
Person.objects.raw(
    '''
    SELECT first AS first_name,
           last AS last_name,
           bd AS birth_date,
           pk AS id,
    FROM some_other_table
    '''
    )

# CASE2
name_map = {
    'first': 'first_name',
    'last': 'last_name',
    'bd': 'birth_date',
    'pk': 'id'
    }

Person.objects.raw(
                    'SELECT * FROM some_other_table',
                     translations=name_map
                  )