Skip to content

Instantly share code, notes, and snippets.

@chairco
Last active August 21, 2018 02:09
Show Gist options
  • Save chairco/2aa930763d1750427ada43ebae0025c9 to your computer and use it in GitHub Desktop.
Save chairco/2aa930763d1750427ada43ebae0025c9 to your computer and use it in GitHub Desktop.

QuerySet 方法

  • filter: = 等於
  • exclude: != 不等於
  • distinct: 去除重複

filter, exclude 方法內參數

  • __exact: 精確等於: 'aaa'
  • __iexact: 精確等於但忽略大小寫 'Aaa'
  • __contains: 包含
  • __icontains: 包含但忽略大小寫
  • __gt: 大於
  • __gte: 大於等於
  • __lt: 小於
  • __lte: 小於等於
  • __in: list 範圍
  • __startswith: 以什麼為開始
  • __istartswith: 以什麼為開始忽略大小寫
  • __endswith: 以什麼為結束
  • __iendswith: 以什麼為結束忽略大小寫
  • __range: 在什麼範圍內
  • __year: 年
  • __month: 月
  • __day: 日
  • __isnull: True/False

aggregate(聚合), annotate(註釋)

  • aggregate: 回傳一個 dict 只包含你想要結果,就像是 Avg, Sum, Count, Max, Min。 p.s 但如果能在 SQL 做還是在 SQL 做掉吧。
  • annotate: 針對每個 object 所以會回傳一整個 queryset,每個 model instance 會有額外 attribute 儲存 annotate 結果
@chairco
Copy link
Author

chairco commented Aug 21, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment