Last active
December 15, 2015 04:59
-
-
Save gregarmer/5206102 to your computer and use it in GitHub Desktop.
Random test cases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import settings | |
import dev_settings as settings | |
from django.core.management import setup_environ | |
setup_environ(settings) | |
from django.db.models import Max | |
from eos.listings.models import Residential | |
from random import randint | |
COUNT = 5 | |
#FILTER = {'imagegallery__isnull': False, 'website_display': True} | |
FILTER = {'website_display': True} | |
EXCLUDE = {'status__in': ['Archived', 'Pending']} | |
def case1(): | |
""" | |
DB case. | |
""" | |
pks = [k['id'] for k in | |
Residential.objects.filter(**FILTER).exclude(**EXCLUDE).values( | |
'id').order_by('?')[:COUNT]] | |
objs = Residential.objects.filter(pk__in=pks, **FILTER).exclude(**EXCLUDE) | |
# Force lazily-evaluated queries to execute | |
len([i for i in objs]) | |
def yield_number_of_random_items(model, maximum_objects, filter_keywords={}, | |
exclude_keywords={}, absolute_max=1000): | |
""" | |
give me a model and a number of items you want to randomly select and | |
I will yield those to you. This is far more efficient than forwarding | |
the random selection to the db by order_by('?'). | |
Any keywords that you would like to/ or not be in the yielded results, | |
please specfy in filter_keywords, exclude_keywords. | |
""" | |
max_ = model.objects.aggregate(Max('id'))['id__max'] | |
i = 0 | |
j = 0 | |
used_ids = [] | |
while i < maximum_objects and j < absolute_max: | |
pk = randint(1, max_) | |
if pk not in used_ids: | |
used_ids.append(pk) | |
filter_keywords['pk'] = pk | |
item = model.objects.filter(**filter_keywords).exclude( | |
**exclude_keywords) | |
if item: | |
yield item[0] | |
i += 1 | |
j += 1 | |
def case2(): | |
""" | |
Python case. | |
""" | |
objs = yield_number_of_random_items(Residential, COUNT, FILTER, EXCLUDE) | |
# Force lazily-evaluated queries to execute | |
len([i for i in objs]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment