Allow for defining translatable fields loosly on the model #30
+258
−2
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
I changed the
TranslatableModelSerializer
to allow for translatable fields to be defined directly on the serializer. This way, you can create flat models which return the translated values for a single language and allow for updating a model in a single language. The language for saving an object is derived from theLanguageCode
field when present. Else it will use the default language detection of Django to determine the language for saving.Reason / Use case
I was using django-hvad, which comes with a serializer which outputs the object in a flat structure as a single translation. I wanted to migrate my API from django-hvad to django-parler without changing the API structure.
Notes
I started out creating a separate
FlatTranslatableModelSerialzer
. When it worked I saw that the logic could be combined into the existingTranslatableModelSerializer
without impacting the existing logic. I also didn't like the name of my new model serializer.Currently, the serializer either pop's the translations field when finding it or it starts popping fields which are translatable. Another take to this would have been to enable/disable the flat structure with a param in init.
I also started out with creating a special
LanguageCode
field, but it seems that the auto-generated field by DRF had all functionality/validation needed. You can easily override the default LanguageCode field using the standard ChoiceField, i.e.:serializers.ChoiceField(choices=settings.LANGUAGES, required=False)