ORM๐Ÿน: ์žฅ๊ณ  QuerySet

์ •์€๊ฒฝยท2020๋…„ 10์›” 15์ผ
0

๐ŸŽธ Play the Djangoย 

๋ชฉ๋ก ๋ณด๊ธฐ
35/57

QuerySet์€ ์–ธ์ œ ํ‰๊ฐ€(evaluate)๋˜๋Š”๊ฐ€?!

  • ์ฟผ๋ฆฌ์…‹์€ ์‹ค์ œ๋กœ DB๋ฅผ hittingํ•˜์ง€ ์•Š๋Š”๋‹ค
  • ๊ทธ๋Ÿผ ์–ธ์ œ DB๋ฅผ hittingํ•˜๋Š” ๊ฐ€?!
    • iteration
      => iteration์„ ์ตœ์ดˆ๋กœ ์‹คํ–‰ํ•  ๋•Œ ํ‰๊ฐ€๋จ
      ์•„๋ž˜์˜ ์ฝ”๋“œ๋Š” ์‚ฌ์šฉํ•˜์ง€ ๋ง๊ฒƒ.
    for e in Entry.objects.all():
        print(e.headline)
    • slicing
      => unevaluated๋œ QuerySet์„ ๋ฆฌํ„ดํ•จ! slicingํ•  ๋•Œ step ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์“ฐ๋ฉด evaluateํ•˜๋ฉด์„œ list๋ฅผ ๋ฐ˜ํ™˜
    • pickling/caching
      => ๊ฒฐ๊ณผ๋ฅผ db๋กœ ๋ถ€ํ„ฐ ์ฝ์–ด์ง
    • repr()
      => repr()์„ ํ˜ธ์ถœํ•  ๋•Œ evaluate ๋จ
      ์ด๋Š” interpreter ํ™˜๊ฒฝ์—์„œ์˜ ํŽธ์˜๋ฅผ ์ œ๊ณตํ•˜๊ธฐ ์œ„ํ•จ!
    • len()
      => len()์„ ํ˜ธ์ถœํ•  ๋•Œ evaluate ๋จ
      record์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๊ณ  ์‹ถ์€ ์šฉ๋„๋กœ๋ผ๋ฉด! len๋ง๊ณ  count ๋ฉ”์†Œ๋“œ๋ฅผ ์“ฐ์„ธ์š”
    • list()
      => force evaluation of a QuerySet by calling list() on it.
    entry_list = list(Entry.objects.all())
    • bool()
      => boolean ๋ฌธ๋งฅ์œผ๋กœ ์‚ฌ์šฉ๋œ, "bool(), or, and, if"์™€ ๊ฐ™์€ ๊ฑฐ๋ž‘ ์“ธ ๋•Œ๋Š” evaluate๋จ
    if Entry.objects.filter(headline="test"):
    	print("There is at least one Entry with the handle Test")
    ์กด์žฌ์œ ๋ฌดํ•œ ์ฒดํฌํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด bool()๋Œ€์‹  exists() ๋ฉ”์†Œ๋“œ ์“ฐ์‚ผ!

Pickling QuerySets

pickle
: ํ”ผํด ๋ชจ๋“ˆ์€ ํŒŒ์ด์ฌ ๊ฐ์ฒด ๊ตฌ์กฐ๋ฅผ serialize/de-serializeํ•˜๊ธฐ ์œ„ํ•œ ๋ฐ”์ด๋„ˆ๋ฆฌ ํ”„๋กœํ† ์ฝœ์„ ๊ตฌํ˜„ํ•œ ๊ฒƒ์ž„
https://docs.python.org/3/library/pickle.html#module-pickle

QuerySet์„ ํ”ผํดํ•˜๋ฉด, ํ”ผํด๋ง๋˜๊ธฐ ์ „์— ๋ฉ”๋ชจ๋ฆฌ์— ๋กœ๋“œํ•˜๋„๋ก ๊ฐ•์ œํ•จ(force)
ํ”ผํด๋ง์€ ์บ์‹œ๋œ ์ฟผ๋ฆฌ์…‹์ด ๋ฆฌ๋กœ๋“œ๋  ๋•Œ, ์บ์‹ฑ์˜ ํ”„๋ฆฌ์ปค์„œ๋กœ์„œ ๋ณดํ†ต ์‚ฌ์šฉ๋จ

This means that when you unpickle a QuerySet, it contains the results at the moment it was pickled, rather than the results that are currently in the database.

Reference

profile
#์˜์‹์˜ํ๋ฆ„ #์ˆœ๊ฐ„์ˆœ๊ฐ„ #์ƒ๊ฐ์˜์Šค๋ƒ…์ƒท

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