๐Ÿƒ๐Ÿผ Django ๋ฉ”์†Œ๋“œ ์ •๋ฆฌ

may_soouuยท2020๋…„ 10์›” 4์ผ
8

Django-ORM

๋ชฉ๋ก ๋ณด๊ธฐ
5/5
post-custom-banner

์žฅ๊ณ ์˜ ๋ฉ”์†Œ๋“œ์— ๋Œ€ํ•ด ์ •๋ฆฌํ•ด๋ณด์ž

ํ•จ์ˆ˜๋‚ด์šฉ
all()ํ…Œ์ด๋ธ” ๋ชจ๋“  ๋ฐ์ดํ„ฐ ์…‹ ๊ฐ€์ ธ์˜ค๊ธฐ
filter()ํŠน์ • ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” ๋ฐ์ดํ„ฐ์…‹ ๊ฐ€์ ธ์˜ค๊ธฐ
exclude()ํŠน์ • ์กฐ๊ฑด์„ ์ œ์™ธํ•œ ๋ฐ์ดํ„ฐ์…‹ ๊ฐ€์ ธ์˜ค๊ธฐ
get()ํŠน์ • ์กฐ๊ฑด์— ๋ถ€ํ•ฉํ•˜๋Š” 1๊ฐœ์˜ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
count()๊ฐ€์ ธ์˜ฌ ๋ฐ์ดํ„ฐ์˜ ๊ฐœ์ˆ˜ ๊ฐ€์ ธ์˜ค๊ธฐ
first()์ฒซ๋ฒˆ์งธ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
last()๊ฐ€์žฅ ๋งˆ์ง€๋ง‰ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
exists()๋ฐ์ดํ„ฐ ์œ ๋ฌด์— ๋Œ€ํ•œ ๊ฒฐ๊ณผ(True, False)๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ
order_by()ํŠน์ • ํ•„๋“œ ์ˆœ์„œ๋Œ€๋กœ ์ •๋ ฌ

1. filter() ์‘์šฉ

1-1. exact

์ผ์น˜ํ•˜๋Š” ์กฐ๊ฑด์„ ์ž…๋ ฅํ•  ๋•Œ ์‚ฌ์šฉ

Boards.objects.filter(title__excact='soohyun')
Boards.objects.filter(title__iexcact='soohyun')
 # iexact๋Š” ๋Œ€์†Œ๋ฌธ์ž๋ฅผ ๊ฐ€๋ฆฌ์ง€ ์•Š๊ณ  ์ผ์น˜ํ•˜๋Š” ์กฐ๊ฑด
  • ์–ธ๋”๋ฐ” ๋‘๊ฐœ (__)
    -์กฐ๊ฑด์„ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ
    -์™ธ๋ถ€ ๋ชจ๋ธ ํ•„๋“œ๋ฅผ ์‚ฌ์šฉํ•  ๊ฒฝ์šฐ

1-2. contains

๋ถ€๋ถ„ ์ผ์น˜ ์กฐ๊ฑด ์ž…๋ ฅํ•  ๋•Œ ์‚ฌ์šฉ

Boards.objects.filter(title__contains='soohyun')
Boards.objects.filter(title__icontains='soohyun')
 # icontains๋Š” ๋Œ€์†Œ๋ฌธ์ž๋ฅผ ๊ฐ€๋ฆฌ์ง€ ์•Š๊ณ  ๋ถ€๋ถ„ ์ผ์น˜ํ•˜๋Š” ์กฐ๊ฑด

1-3. in

์—ฌ๋Ÿฌ ์กฐ๊ฑด์„ ํฌํ•จํ•  ๊ฒฝ์šฐ ์‚ฌ์šฉ

Boards.objects.filter(title__in=['soohyun','developer'])

1-4. gt / lt / gte / lte

gt (greater than) : >
lt (less than) : <
gte (greater than or equal) : >=
lte (less than or equal) : <=

Boards.objects.filter(registered_date__gt=datetime.date(2020.10.04)
Boards.objects.filter(registered_date__lt=datetime.date(2020.10.04)

1-5. startswith / endswith

startswith : ์กฐ๊ฑด์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰
endswith : ์กฐ๊ฑด์œผ๋กœ ๋๋‚˜๋Š” ๋ฌธ์ž์—ด ๊ฒ€์ƒ‰

Boards.objects.filter(title__startswith="book")

1-6. union

๋‘ ๊ฐœ ์ด์ƒ์˜ ์ฟผ๋ฆฌ์…‹ ๋ณ€์ˆ˜๋ฅผ ํ•˜๋‚˜์˜ ์ฟผ๋ฆฌ์…‹ ๊ฐ’์œผ๋กœ ํ•ฉ์นœ๋‹ค.

data1 = Boards.objects.filter(title__exact="soohyun")
data2 = Boards.objects.filter(title__exact="developer")
data3 = union(data1, data2)

1-7. intersection()

๊ต์ง‘ํ•ฉ์œผ๋กœ ๋‘ ๊ฐœ ์ด์ƒ์˜ ์ฟผ๋ฆฌ์…‹ ๋ณ€์ˆ˜ ์ค‘ ์ค‘๋ณต๋œ ๊ฐ’์„ ๊ฐ€์ง€๊ณ  ์˜จ๋‹ค

data1 = Boards.objects.filter(title__in=["soohyun", "developer"])
data2 = Boards.objects.filter(title__in=["soohyun", "wecode"])
data3 = intersection(data1, data2)

๊ฒฐ๊ณผ๋Š” title ์ด soohyun์ธ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์˜จ๋‹ค.

profile
back-end ๊ฐœ๋ฐœ์ž
post-custom-banner

1๊ฐœ์˜ ๋Œ“๊ธ€

comment-user-thumbnail
2023๋…„ 8์›” 11์ผ

๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

๋‹ต๊ธ€ ๋‹ฌ๊ธฐ