I am trying to access querystring values in serializer class.
我试图访问序列化程序类中的查询字符串值。
class OneZeroSerializer(rest_serializer.ModelSerializer):
location = rest_serializer.SerializerMethodField('get_alternate_name')
def get_alternate_name(self, obj):
view = self.context['view']
print view.kwargs['q'] #output is {}
return 'foo'
class Meta:
model = OneZero
fields = ('id', 'location')
Views
查看
class OneZeroViewSet(viewsets.ModelViewSet):
serializer_class = OneZeroSerializer
queryset = OneZero.objects.all()
Is this right way to access querystring?
这是访问查询字符串的正确方法吗?
3 个解决方案
#1
22
When using ViewSets, you can access the request in the serializer context (like you access the view). You can access the query params from this
使用ViewSets时,您可以在序列化程序上下文中访问请求(就像访问视图一样)。您可以从中访问查询参数
def get_alternate_name(self, obj):
request = self.context['request']
print request.QUERY_PARAMS['q']
return 'foo'
The attribute view.kwargs contains the named arguments parsed from your url-config, so from the path-part.
属性view.kwargs包含从url-config解析的命名参数,因此来自path-part。
#2
8
According to the docs you want to use self.request.QUERY_PARAMS
根据您要使用的文档self.request.QUERY_PARAMS
You can see it being used here
你可以在这里看到它被使用
UPDATE:
更新:
As of DRF 3.0:
从DRF 3.0开始:
The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params
request.QUERY_PARAMS的使用现在正在等待弃用,以支持小写的request.query_params
#3
1
self.context['request'].query_params
self.context [ '请求']。query_params
#1
22
When using ViewSets, you can access the request in the serializer context (like you access the view). You can access the query params from this
使用ViewSets时,您可以在序列化程序上下文中访问请求(就像访问视图一样)。您可以从中访问查询参数
def get_alternate_name(self, obj):
request = self.context['request']
print request.QUERY_PARAMS['q']
return 'foo'
The attribute view.kwargs contains the named arguments parsed from your url-config, so from the path-part.
属性view.kwargs包含从url-config解析的命名参数,因此来自path-part。
#2
8
According to the docs you want to use self.request.QUERY_PARAMS
根据您要使用的文档self.request.QUERY_PARAMS
You can see it being used here
你可以在这里看到它被使用
UPDATE:
更新:
As of DRF 3.0:
从DRF 3.0开始:
The usage of request.QUERY_PARAMS is now pending deprecation in favor of the lowercased request.query_params
request.QUERY_PARAMS的使用现在正在等待弃用,以支持小写的request.query_params
#3
1
self.context['request'].query_params
self.context [ '请求']。query_params