ある条件下で、Qオブジェクトを使ってOR演算すると期待した通りにならない
原因がわからないので、後で調べるためにメモしておく。
環境はPython2.5、Django0.96、WindowsVista・XPで確認した。
例えばこんなモデルがあったとして、
from django.db import models class GrandChild(models.Model): name = models.CharField(maxlength=100) class ChildFirst(models.Model): name = models.CharField(maxlength=100) grandchildren = models.ManyToManyField(GrandChild) class ChildSecond(models.Model): name = models.CharField(maxlength=100) grandchildren = models.ManyToManyField(GrandChild) class Parent(models.Model): name = models.CharField(maxlength=100) first = models.ForeignKey(ChildFirst, null=True, blank=True) second = models.ForeignKey(ChildSecond, null=True, blank=True)
子1の孫をキーにして、親を検索したい場合はこう書く。
Parent.objects.filter(first__grandchildren__id=1) #ID=1の場合
子2の孫をキーにする場合はこう。
Parent.objects.filter(second__grandchildren__id=1) #ID=1の場合
どちらも期待した結果が得られる。
が、子1または子2の孫をキーにして検索しようとしてこう書くと、結果は空になる。謎だ。
Parent.objects.filter(Q(first__grandchildren__id=1) | Q(second__grandchildren__id=1))