django-modeltranslation icon indicating copy to clipboard operation
django-modeltranslation copied to clipboard

order_by does not incorporate the fallback language

Open Mactory opened this issue 9 years ago • 1 comments

When using order_by on a translated model field, the fallback language is not used if the current language's field is empty. e.g: I have a class with a name field that is translated into German (de) and English (en). I set english as fallback language. I then make sure each model instance has the name_en correctly set. Some of them also have the name_deset.

If I activate German as language and then have a view displaying all model instances ordered by name, the following happens: All instances with a name_de that is set are correctly ordered and their names are displayed in German. Those without German translations correctly display the English fallback values but are out of order, as they were ordered by the NULL value of the name_de field in the database.

This is of course a result of the query using an ORDER BY "name_de" which results in the NULL values being either at the front or at the back. A solution would be to use ORDER BY COALESCE("name_de", "name_en") so that the fallback language would be used for those rows with empty translated valued.

Mactory avatar Jan 05 '16 10:01 Mactory

I seem to have the same issue (actually stumbled upon it a couple of times now). I believe this can be remedied by setting MODELTRANSLATION_AUTO_POPULATE = True. But

  • This would increase the size of the database tremendously
  • I am still figuring out how to trigger population of existing objects. Model.objects.all().populate(True).update(translatable_field=F('translatable_field')) does not do it, for instance.
  • This does it, but is slow and clunky:
for obj in Model.objects.all():
    if not obj.translatable_field_lang:
        obj.translatable_field_lang = obj.translatable_field_defaultlang
        obj.save()

@Mactory have you found another workaround in the meantime?

sebphi avatar May 28 '18 08:05 sebphi