๐Ÿ‘Š๐Ÿป ์žฅ๊ณ  Q() & F() ์ดํ•ดํ•˜๊ธฐ

may_soouuยท2020๋…„ 9์›” 27์ผ
13

Django-ORM

๋ชฉ๋ก ๋ณด๊ธฐ
2/5
post-thumbnail

1. Q()

1-1. Q ์‚ฌ์šฉ

Q๋Š” ์–ธ์ œ ์‚ฌ์šฉํ• ๊นŒ?
Q๋Š” ์žฅ๊ณ  model orm์œผ๋กœ where ์ ˆ์— or๋ฌธ์„ ์ถ”๊ฐ€ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•œ๋‹ค.

1) or ์กฐ๊ฑด

from django.db.models import Q
 # Q๋ฅผ ๋จผ์ € ์ž„ํฌํŠธ ํ•ด์ค˜์•ผํ•œ๋‹ค.
 
Products.object.filter(Q(name='backpack')|Q(price='9900'))
 # ๋„ค์ž„์ด backpack ์ด๊ฑฐ๋‚˜ ๊ฐ€๊ฒฉ์ด 9900์›์ธ ๊ฒƒ
 == ๋™์ผํ•œ ๊ฒฐ๊ณผ๊ฐ€
 SELECT * FROM products WHERE name='backpack' or price='9900'

2) and ์กฐ๊ฑด

Products.objects.filter(Q(name='backpakc') & Q(no=12312))

3) not ์กฐ๊ฑด

> 2๊ฐ€์ง€ ๋ฐฉ๋ฒ•์ด ์žˆ๋‹ค
 > exclude()
 > filter(~Q())
 
 ex. id < 5 ๋ผ๋Š” ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜์ง€ ์•Š๋Š” ๋ชจ๋“  ์‚ฌ์šฉ์ž
 1. exclude()
 >> queryset = User.objects.exclude(id__lt=5)

 2. filter(~Q())
 >> from django.db.models import Q
 >> queryset = User.objects.filter(~Q(id__lt=5))

1-2. Q ์กฐ๊ฑด ์—ฐ๊ฒฐ

Q๋ฅผ ์ฒ˜์Œ์— ์„ ์–ธํ•œ ํ›„, add ๋กœ ๊ฐ’์„ ์ถ”๊ฐ€ํ•  ๋•Œ ์ฒ˜์Œ ์„ ์–ธ๋œ ์•ž์˜ ์กฐ๊ฑด๊ณผ ์—ฐ๊ฒฐ๋œ๋‹ค.

q = Q(no=1)
q.add(name='back', q.OR)
 # no=1 or name = 'back'

2. F()

F()๊ฐ์ฒด๋Š” ์–ธ์ œ ์‚ฌ์šฉํ• ๊นŒ?

ํŒŒ์ด์ฌ์œผ๋กœ ๋ฉ”๋ชจ๋ฆฌ๋ฅผ ๊ฐ€์ ธ์˜ค์ง€ ์•Š๊ณ , ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ๋‚ด์—์„œ ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•  ๋•Œ

๊ฐ„๋‹จํ•œ ์˜ˆ์ œ

 # F๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ๋•Œ
reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed += 1
reporter.save()

 # F๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ
from django.db.models import F

reporter = Reporters.objects.get(name='Tintin')
reporter.stories_filed = F('stories_filed') + 1
reporter.save()

2-1. F() ์‚ฌ์šฉ๋ฒ•

SELECT a, b, c, d
FROM product
WHERE a=c

f()๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํ‘œํ˜„ํ•œ๋‹ค๋ฉด

from django.db.models import F

product.objects.filter(a=F('c'))

์•„์ง ์ •๋ฆฌ์ค‘,,,

profile
back-end ๊ฐœ๋ฐœ์ž

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

comment-user-thumbnail
2021๋…„ 2์›” 16์ผ

ํฌ์ŠคํŒ… ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

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