Created
May 26, 2010 22:15
-
-
Save acdha/415151 to your computer and use it in GitHub Desktop.
Using @simonw's django-queryset-transform to avoid massive performance penalties with translated model content
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
@classmethod | |
def localized(cls, lang=u'en'): | |
""" | |
Returns a QuerySet which will be pre-populated with localized values | |
Usage: | |
Item.localized("en").filter(…) | |
""" | |
if not isinstance(lang, Language): | |
lang = Language.objects.get(iso639_3=lang) | |
return cls.objects.all().transform(partial(langify_transformer, lang=lang)) |
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
def langify_transformer(qs, lang=None): | |
""" | |
Helper used with django-queryset-transform to fetch the localization data | |
needed once per queryset rather than per item, improving performance from | |
O(N) to O(1). | |
""" | |
item_pks = [item.pk for item in qs] | |
langify_fields = ('description', 'title') # TODO: Make this list real | |
descriptions = dict(Description.objects.filter(language=lang, item__in=item_pks).values_list("item_id", "value")) | |
titles = dict(ItemTitle.objects.filter(item__in=item_pks, language=lang).values_list("item_id", "value")) | |
for item in qs: | |
for k in langify_fields: | |
assert not hasattr(item, k), "Can't transform %s: conflict with pre-existing %s field!" % (item, k) | |
item.description = descriptions[item.pk] | |
item.title = titles[item.pk] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment