在Django Rest框架中的ViewSet和Serializer中访问请求对象? [英] Accessing Request Object in Viewset and Serializers in Django Rest Framework?

查看:530
本文介绍了在Django Rest框架中的ViewSet和Serializer中访问请求对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想访问我的Views.py中的请求对象和DRF中的Serializers.py。
我的Views.py:

I want to access the request object in my Views.py and Serializers.py in DRF. My 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:

My 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对象没有属性'request'。另外在views.py我得到 NameError:name'request'未定义

In Serializers.py I get ProductSerializer' object has no attribute 'request'. Also In views.py I get NameError: name 'request' is not defined

如何访问请求对象?我必须将其从视图传递给序列化程序吗? views.py和serializers.py有什么区别?一般来说,我将所有的业务逻辑写在Views.py中;这里也应该在视图中执行所有查询/过滤器,或者我应该在序列化器中执行它们,或者它们没有任何作用。

How do I access request object? Do I have to pass it from views to serializers? Also what's the difference between views.py and serializers.py? Generally I write all the business logic in Views.py ; here also should I do all the queries/filters in the views or should I do them in serializers or it doesn't make a difference. New to DRF please help.

推荐答案

您不需要包含请求请求对象传递给序列化程序上下文。

You don't need to include request object in the context as the generic views passes request object to the serializer context.

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
    }

在您的序列化器中,您可以 使用 .context 属性访问请求对象

In your serializer, you can access the request object using .context attribute.


上下文字典可以是在任何序列化器字段逻辑中使用
,如自定义 .to_representation()方法,通过访问
self.context 属性

The context dictionary can be used within any serializer field logic, such as a custom .to_representation() method, by accessing the self.context attribute.



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

这篇关于在Django Rest框架中的ViewSet和Serializer中访问请求对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆