Query

OR query

from functools import reduce
from operator import or_
from django.db.models import Q

values = [1, 2, 3]
query = reduce(or_, (Q(pk=x) for x in values))

REFERENCES:

  • https://stackoverflow.com/questions/852414/how-to-dynamically-compose-an-or-query-filter-in-django
  • https://qiita.com/shati-taro/items/977ed91243ee99c9465f

Pluck

XXX.objects.values("name", "id")[1].get("id")

QueryStringify

>>> queryset = MyModel.objects.all()
>>> print(queryset.query)
SELECT "myapp_mymodel"."id", ... FROM "myapp_mymodel"

Filter

XXX.objects.filter(name="ABCさん")

district_count

Company.objects.values("name").distinct().count()

Count

>>> import django.db.models

>>> likes = Like.objects.all().select_related("comment", "note")
>>> users = MyUser.objects.prefetch_related(Prefetch("like_set", queryset=likes), "following", "followers")
>>> user = users.get(pk=11)
>>>
>>> user.like_set.filter(comment_id__isnull=False).count()
>>> user.like_set.aggregate(value=Sum(Case(When(note_id__isnull=False, then=1), default=0),output_field=IntegerField()))["value"]