Cod*_*mon 10 python django django-rest-framework
我想在DRF中的Views.py和Serializers.py中访问请求对象.我的Views.py:
class ProductViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions.
    """
    queryset = Product.objects.all()
    serializer_class = ProductSerializer(context={'request': request})
我的Serializers.py:
class ProductSerializer(serializers.HyperlinkedModelSerializer):
    get_sr_price = serializers.SerializerMethodField('get_sr_price_func')
    def get_sr_price_func(self, obj):
        return self.request.user ??
    class Meta:
        model = Product
        fields = (
            'title', 'slug', 'product_stores', 'get_sr_price')
在Serializers.py中,我得到了ProductSerializer' object has no attribute 'request'.另外在views.py中我得到了NameError: name 'request' is not defined
我如何访问请求对象?我是否必须将它从视图传递给序列化程序?那还有views.py和serializers.py之间的区别是什么?通常我会在Views.py中编写所有业务逻辑; 我还应该在视图中执行所有查询/过滤器,还是应该在序列化程序中执行它们,或者它没有任何区别.DRF新手请帮忙.
Rah*_*pta 26
request由于通用视图将request对象传递给序列化程序上下文,因此您无需在上下文中包含对象.
DRF源代码段:
# rest_framework/generics.py
def get_serializer_context(self):
    """
    Extra context provided to the serializer class.
    """
    return {
        'request': self.request, # request object is passed here
        'format': self.format_kwarg,
        'view': self
    }
在你的序列化,你可以访问的request使用对象.context的属性.
通过访问属性,
context可以在任何序列化器字段逻辑(例如自定义.to_representation()方法)中 使用该字典self.context.
class ProductSerializer(serializers.HyperlinkedModelSerializer):
    get_sr_price = serializers.SerializerMethodField('get_sr_price_func')
    def get_sr_price_func(self, obj):
        return self.context['request'].user # access the request object
| 归档时间: | 
 | 
| 查看次数: | 9585 次 | 
| 最近记录: |