| 220 | |
| 221 | # OR lookups across foreign keys |
| 222 | # |
| 223 | # At revision 3077, the last test cases fail to find a reporter with |
| 224 | # no articles. For someone not familiar with how the ORM works |
| 225 | # internally, it's quite unexpected. |
| 226 | # |
| 227 | >>> from django.db.models import Q |
| 228 | |
| 229 | # Check that all is ok when all reporters queried do have articles: |
| 230 | >>> Reporter.objects.filter(Q(first_name='John') | |
| 231 | ... Q(article__headline__startswith='Paul')).distinct() |
| 232 | [<Reporter: John Smith>, <Reporter: Paul Jones>] |
| 233 | >>> (Reporter.objects.filter(first_name='John') | |
| 234 | ... Reporter.objects.filter(article__headline__startswith='Paul')).distinct() |
| 235 | [<Reporter: John Smith>, <Reporter: Paul Jones>] |
| 236 | |
| 237 | # Create a new reporter Luke with no articles. |
| 238 | >>> r3 = Reporter(first_name='Luke', last_name='Field', email='luke@example.com') |
| 239 | >>> r3.save() |
| 240 | |
| 241 | # These queries fail to match the reporter with no articles: |
| 242 | >>> Reporter.objects.filter(Q(first_name='Luke') | |
| 243 | ... Q(article__headline__startswith='Paul')).distinct() |
| 244 | [<Reporter: Luke Field>, <Reporter: Paul Jones>] |
| 245 | >>> (Reporter.objects.filter(first_name='Luke') | |
| 246 | ... Reporter.objects.filter(article__headline__startswith='Paul')).distinct() |
| 247 | [<Reporter: Luke Field>, <Reporter: Paul Jones>] |
| 248 | |
| 249 | # Maybe the problem is that an inner join is used instead of a left |
| 250 | # outer join? |
| 251 | >>> 'INNER JOIN' in (Reporter.objects.filter(first_name='Luke') | |
| 252 | ... Reporter.objects.filter(article__headline__startswith='Paul')).distinct()._get_sql_clause()[1] |
| 253 | False |
| 254 | |
| 255 | # Clean up |
| 256 | >>> r3.delete() |
| 257 | |
| 258 | |