LoginSignup
4
3

More than 5 years have passed since last update.

【DjangoのModel】OR条件のクエリをつくる方法

Last updated at Posted at 2018-12-04

この記事で書いていること

  • Qオブジェクトを使って、DjangoでOR条件を作れるという話
  • 公式DOCSの以下の部分を参考にしてます

Qオブジェクトを使って実装する

例えば、pub_dateというDateTimeFieldを持つPollというモデルを持っているとして。

pub_dateが2018年の12月1日 or 12月3日のインスタンスを取得したい場合、以下のように書けます。

from django.db.models import Q

Poll.objects.get(
    Q(pub_date=date(2018, 12, 1)) | Q(pub_date=date(2018, 12, 3))
)

filter, exclude, getなどの検索関数に渡すことができる

上の例でもすでに示していることですが。

filter()、exclude()、get()と言った、検索関数に対して、複数のQオブジェクトを渡すことができます。

上の例に、「questionが"Who"と言う文字列から始まる」と言う条件も付け加えたのが、以下のコード。

from django.db.models import Q

Poll.objects.get(
    Q(question__startswith='Who'),
    Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)

「questionが"Who"と言う文字列から始まる」  AND 「pub_dateが 2018年12月1日 OR  2018年12月3日」

という意味のクエリが発行されます。

簡単ですが、以上です。

4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3