Skip to content

Instantly share code, notes, and snippets.

@yellowcap
Last active August 29, 2015 14:08
Show Gist options
  • Save yellowcap/81c6d5f3ea1426689c80 to your computer and use it in GitHub Desktop.
Save yellowcap/81c6d5f3ea1426689c80 to your computer and use it in GitHub Desktop.
Django-parler integrated with Django-Rest-Framework for read only applications. When using these classes to create ModelViewSet endpoints, you can select the language using query parameters. For example /api/mymodel/?language=fr
from rest_framework import serializers
class ParlerModelSerializer(serializers.ModelSerializer):
"""Serializer to handle django-parler fields"""
def __init__(self, *args, **kwargs):
# Get list of translated fields
fields = self.Meta.model._translations_model.get_translated_fields()
# Separate parler fields and scilent fields
parler_fieds = [x for x in self.Meta.fields if x in fields]
pas_parler_fields = [x for x in self.Meta.fields if x not in fields]
# Remove parler fields from default serializer instantiation
self.Meta.fields = pas_parler_fields
# Instantiate default serializer without transtlated fields
super(ParlerModelSerializer, self).__init__(*args, **kwargs)
# Add requested serializer fields
for field in parler_fieds:
self.fields[field] = serializers.Field(source=field)
# Restore original meta fields
self.Meta.fields += parler_fieds
from rest_framework import serializers, viewsets
class ParlerModelViewSet(viewsets.ModelViewSet):
"""View set that pre-filters to a django-parler language"""
def get_queryset(self):
# Get default queryset
queryset = super(viewsets.ModelViewSet, self).get_queryset()
# Get language from query parameters
language = self.request.QUERY_PARAMS.get('language', None)
# Update language of queryset accordingly
if language is not None:
queryset = queryset.language(language)
return queryset
@yellowcap
Copy link
Author

An alternative and more complete integration can also be found in the following gist (which inspired this one)
https://gist.github.com/vdboor/a4629d7f3d4158f3a229

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment