KristianOellegaard / django-hvad

Painless translations in django, using the regular ORM. Integrates easily into existing projects and apps. Easy convertible from django-multilingual-ng.
https://github.com/KristianOellegaard/django-hvad
Other
533 stars 127 forks source link

Return default language value for field if translated value is null / empty #331

Closed daesu closed 7 years ago

daesu commented 7 years ago

Hi all,

I guess I am missing something very straight forward here but I can't seem to find the answer.

I am using DRF with hvad and currently there are 2 supported languages. The default language is English and required fields contain values. For some fields there may or may not be a translated equivalent.

For example, there is a URL link to a video for some model. There is a requirement wherein the model may need to return a different URL depending on the language. (i.e. the same video but in the translated language).

In most cases however the value will be the same.

How can I make this URL field return the default language (English) value if the translated value is empty? (It's a charfield).

Thank you.

spectras commented 7 years ago

Hello!

Well, hvad does not have the concept of a default language. All translations are equal and treated as such. You can specify a fallbacks chain when querying for a language, but it applies to the translation as a whole, not field-by-field. Thus, if your object has a translation in some language, then all fields will use that translation.

What you want to do is completely possible, but you'll have to implement the logic by yourself. Basically, that means at some point, either in your views or client-side, you must load both the language you want and the language you want to use as a default, and use your own logic to display either depending on some condition or, why not, both side by side.

If your REST api is intended for displaying only, doing this server-side to hide the implementation detail of how the video is chosen makes sense. On the other hand, if your REST api is read-write to allow editing the fields, it should simply expose the fact that the video is null and let your javascript load another language if it so wishes.

daesu commented 7 years ago

Thanks for that @spectras