将参数传递给Django REST框架序列化程序以与模型一起使用

时间:2017-08-24 08:00:08

标签: django django-rest-framework django-serializer

我有一个类Object,其方法state采用日期时间参数dt。如何将URL中的datetime参数传递给Object.state()

模特:

class Object(models.Model):
    def state(self, dt=datetime.datetime.now()) -> dict:
        ...stuff...
        return {'dt': dt, 'other_stuff': stuff}

观点:

class ObjectDetail(generics.RetrieveAPIView):
    queryset = models.Object.objects.all()
    serializer_class = serializers.ObjectSerializer

    def get_serializer_context(self):
        return {'dt': self.request.query_params.get('dt', datetime.datetime.now())}

    def get(self, request, *args, **kwargs):
        return self.retrieve(request, *args, **kwargs)

序列化器类:

class ObjectSerializer(serializers.HyperlinkedModelSerializer):
    state = StateSerializer(read_only=True, context={'dt': self.context['dt']})

    class Meta:
        model = models.Object
        fields = ('state')

class StateSerializer(serializers.Serializer):
    dt = serializers.DateTimeField()
    ... other stuff...

正如您所看到的,我正在尝试将dt作为额外的上下文传递到已在视图中设置上下文的行state = StateSerializer(read_only=True, context={'dt': dt})中。这里的问题是,ObjectSerializer初始化时dt无法通过self.context['dt']访问,因为self未定义。

1 个答案:

答案 0 :(得分:2)

解决方案是让<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <app.test.Componenets.PlusTabLayout.TabLayoutPlus android:id="@+id/celebrityMovieFrag_tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/actionBarSize" android:paddingBottom="@dimen/size3" android:paddingLeft="@dimen/size3" android:paddingRight="@dimen/size3" app:tabIndicatorColor="@color/colorAccent" app:tabSelectedTextColor="@color/colorAccent" app:tabTextAppearance="@style/allCapsTabLayout" app:tabTextColor="@color/darkBlueGrey" /> <app.test.Componenets.DisableSwipeViewPager android:id="@+id/celebrityMovieFrag_viewPager" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/celebrityMovieFrag_tabLayout" /> </RelativeLayout> </android.support.v4.widget.NestedScrollView> </RelativeLayout> 成为state,然后定义serializers.SerializerMethodField()方法。新get_state看起来像这样:

ObjectSeializer