1👍
✅
First of all, if you want speed – you should try caching.
You can also optimize your query.
def get_city(self):
user_lang = get_language() # en
return CitiesTranslations.objects.get(
city=self.city_id, lang_group__group__iso_code=user_lang
).common_name
What you probably also want is to get all your stuff in batches, not with individual method calls. Assuming we have your object_list
:
city_ids = [x.city_id for x in object_list]
city_translations = CitiesTranslations.objects.filter(
city__in=city_ids, lang_group__group__iso_code=user_lang
).values_list('city_id', 'common_name')
city_translations = dict(city_translations)
for obj in object_list:
obj.city_name = city_translations[obj.city_id]
You can put this code somewhere in your view. You will also have to change {{ item.get_city }}
to {{ item.city_name }}
in the templates.
Source:stackexchange.com