`HyperlinkedIdentityField`需要序列化程序上下文中的请求

时间:2018-03-28 06:28:08

标签: nested django-rest-framework serializer

我已经尽力了,但没有什么对我有用

我的模特:

model Parent():
    ...
model Child():
    owner = models.ForeignKey(Parent, on_delete=models.CASCADE,
                          related_name='children')
    ...

我的网址:

router = routers.DefaultRouter()
router.register(r'parents', ParentViewSet, base_name="parents")
router.register(r'childs', ChildViewSet, base_name="childs")

urlpatterns = [
    path('api/', include(router.urls)),
]

我的序列化器:

class ParentSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name="parent-detail", lookup_field='pk')
    children = serializers.SerializerMethodField()
    class Meta:
        model = User
        fields = (
            ...
            'children')

    def get_children(self, obj):
        queryset = Child.objects.filter(owner=obj)
        children = ChildSerializer(queryset, many=True).data
        return children

class ChildSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name="child-detail", lookup_field='pk')
    ...

我的观看次数:

class ParentViewSet(SerializerByActionMixin, LoggingMixin, viewsets.ModelViewSet):

queryset = Parent.objects.all().prefetch_related('children').order_by('-date_joined')
serializers = {
    'default': ParentSerializer,
    'create': ParentCreateSerializer,
    'update': ParentUpdateSerializer,
}

class ChildViewSet(LoggingMixin, viewsets.ModelViewSet):

queryset = Child.objects.all().order_by('-timestamp')
serializer_class = ChildSerializer
http_method_names = ['get', 'put', 'patch', 'head']

我的问题:     HyperlinkedIdentityField需要序列化程序上下文中的请求。实例化序列化程序时添加context={'request': request}。 我读过这篇文章,但不知道我的代码在哪里粘贴这个上下文。 请帮忙。谢谢!

1 个答案:

答案 0 :(得分:2)

正如文档所述,您需要在上下文中提出请求:

class ParentSerializer(serializers.ModelSerializer):
    ...
    def get_children(self, obj):
        queryset = Child.objects.filter(owner=obj)
        children = ChildSerializer(queryset, many=True, context=self.context).data
        return children