Ticket #2080: m2o_or_lookup_test.2.diff

File m2o_or_lookup_test.2.diff, 2.1 KB (added by Antti Kaihola, 18 years ago)

Added testing with alternate syntax and checking what kind of join Django uses

  • modeltests/many_to_one/models.py

     
    217217>>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct()
    218218[<Reporter: John Smith>]
    219219
     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]
     253False
     254
     255# Clean up
     256>>> r3.delete()
     257
     258
    220259# If you delete a reporter, his articles will be deleted.
    221260>>> Article.objects.all()
    222261[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>, <Article: This is a test>, <Article: This is a test>]
Back to Top