1 | #!/usr/bin/env python
|
---|
2 |
|
---|
3 | import os
|
---|
4 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'bugrep.settings')
|
---|
5 |
|
---|
6 | import django
|
---|
7 | from django.db.models import Count
|
---|
8 | from bugrep.models import *
|
---|
9 |
|
---|
10 | Alfa.objects.all().delete()
|
---|
11 | Bravo.objects.all().delete()
|
---|
12 | Charlie.objects.all().delete()
|
---|
13 |
|
---|
14 | b = Bravo.objects.create()
|
---|
15 | c = Charlie.objects.create(bravo=b)
|
---|
16 |
|
---|
17 | qsboth = Charlie.objects.select_related('alfa').annotate(Count('bravo__charlie'));
|
---|
18 | print('select_related + annotate: %i rows' % qsboth.count())
|
---|
19 | print(str(qsboth.query) + '\n')
|
---|
20 |
|
---|
21 | qsboth_rev = Charlie.objects.annotate(Count('bravo__charlie')).select_related('alfa');
|
---|
22 | print('annotate + select_related: %i rows' % qsboth_rev.count())
|
---|
23 | print('identical query? ' + ('yes' if str(qsboth_rev.query) == str(qsboth.query) else 'no') + '\n')
|
---|
24 |
|
---|
25 | qsselrel = Charlie.objects.select_related('alfa');
|
---|
26 | print('select_related: %i rows' % qsselrel.count())
|
---|
27 | print(str(qsselrel.query) + '\n')
|
---|
28 |
|
---|
29 | qsanno = Charlie.objects.annotate(Count('bravo__charlie'));
|
---|
30 | print('annotate: %i rows' % qsanno.count() + '\n')
|
---|
31 |
|
---|
32 | print('Trying with non-null alfa\n')
|
---|
33 |
|
---|
34 | a = Alfa.objects.create()
|
---|
35 | Charlie.objects.update(alfa=a)
|
---|
36 |
|
---|
37 | qsboth_nn = Charlie.objects.select_related('alfa').annotate(Count('bravo__charlie'));
|
---|
38 | print('select_related + annotate: %i rows' % qsboth_nn.count())
|
---|
39 | print('identical query? ' + ('yes' if str(qsboth_nn.query) == str(qsboth.query) else 'no') + '\n')
|
---|
40 |
|
---|
41 | qsboth_nn_rev = Charlie.objects.annotate(Count('bravo__charlie')).select_related('alfa');
|
---|
42 | print('annotate + select_related: %i rows' % qsboth_nn_rev.count())
|
---|
43 | print('identical query? ' + ('yes' if str(qsboth_nn_rev.query) == str(qsboth.query) else 'no') + '\n')
|
---|
44 |
|
---|
45 | print('Django version: ' + django.get_version())
|
---|