this is the api which sets language when user selects some language this works fine.
class SetLanguage(APIView):
def get(self, request, *args, **kwargs):
user_language = kwargs.get("lan_code")
translation.activate(user_language)
response = Response(status=status.HTTP_200_OK)
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, user_language)
request.session[LANGUAGE_SESSION_KEY] = user_language
return response
viewset
here with this viewset only in the api blog/{id}
the function get_language
returning default language code but on other api it working properly. I am not being able to find the issue.
What might gone wrong ?
class BlogViewSet(ModelViewSet):
queryset = Blog.l_objects.all()
serializer_class = BlogSerilizer
detail_serializer_class = BlogDetailSerializer
def get_serializer_class(self):
if self.action == "retrieve":
return self.detail_serializer_class
return super().get_serializer_class()
def list(self, request, *args, **kwargs):
queryset = Blog.l_objects.filter(parent=None)
serializer = self.get_serializer(queryset, many=True)
return Response(serializer.data)
@action(detail=True, methods=["get"])
def childs(self, request, id):
child_blogs = Blog.l_objects.filter(parent_id=id)
serializer = self.get_serializer(child_blogs, many=True)
return Response(serializer.data)
model
from django.utils.translation import get_language
class MyManager(models.Manager):
def get_queryset(self):
current_language = get_language()
print(current_language)
return super().get_queryset().filter(language=current_language)
class Blog(models.Model):
title = models.CharField(_("Title"), max_length=100)
objects = models.Manager()
l_objects = MyManager()
What can be the possible issue?
CodePudding user response:
Your viewset is defined as:
class BlogViewSet(ModelViewSet):
queryset = Blog.l_objects.all()
...
Here the point to be noticed is that your queryset gets defined at the module level. Hence your managers get_queryset
is called. Considering there has been no requests yet get_language()
returns the default language and this is then reused everywhere since the default implementation of the get
method will just call the viewset's get_queryset
which will then call .all()
on the specified queryset hence your expectation of your manager's get_queryset
being called each request doesn't occur and the default language queryset is reused everywhere.
To solve this you can just write a get_queryset
method for the viewset, forcing creation of a new queryset each time:
class BlogViewSet(ModelViewSet):
queryset = Blog.l_objects.all()
serializer_class = BlogSerilizer
detail_serializer_class = BlogDetailSerializer
def get_queryset(self):
return Blog.l_objects.all()
...