我在序列化多对多关系后遇到此错误,这在没有URL的情况下工作正常但由于某种原因我在尝试包含它时遇到此错误。
`InitiativeUrlHyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
以下是我的观点和序列化程序。
Views.py
class CreateInitiativeAPIView(generics.CreateAPIView):
serializer_class = CreateInitiativeSerializer
class InitiativeListAPIView(generics.ListAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
serializer_class = InitiativeListSerializer
permission_classes = [permissions.IsAuthenticated]
queryset = Initiative.objects.all()
class InitiativeDetailAPIView(generics.RetrieveAPIView):
authentication_classes = [SessionAuthentication, BasicAuthentication, JSONWebTokenAuthentication]
serializer_class = InitiativeFullSerializer
permission_classes = [permissions.IsAuthenticated]
lookup_field = 'id'
def get_object(self):
initiative_id = self.kwargs["initiative_id"]
obj = get_object_or_404(Initiative, id=initiative_id)
return obj
def put(self, request, *args,**kwargs):
return self.update(request, *args, **kwargs)
Serializers.py
class InitiativeUrlHyperlinkedIdentityField(serializers.HyperlinkedIdentityField):
def get_url(self, obj, view_name, request, format):
kwargs = {
'initiative_id': obj.id,
}
return reverse(view_name, kwargs=kwargs, request=request, format=format)
class CreateInitiativeSerializer(serializers.ModelSerializer):
class Meta:
model = Initiative
fields = ['name', 'description', 'image', 'goal']
class InitiativeListSerializer(serializers.ModelSerializer):
url = InitiativeUrlHyperlinkedIdentityField("initiative_detail_api", lookup_field='id')
class Meta:
model = Initiative
fields = [
'url',
'name',
]
class InitiativeFullSerializer(serializers.ModelSerializer):
url = InitiativeUrlHyperlinkedIdentityField("initiative_detail_api", lookup_field='id')
class Meta:
model = Initiative
fields = [
'url',
'id',
'name',
'description',
'image',
'goal']
这是从InitiativeFullSerializer获取信息的序列化程序。
class ChapterInitiativePartialListSerializer(serializers.ModelSerializer):
initiative = InitiativeFullSerializer(many=False, read_only=True)
class Meta:
model = ChapterInitiative
fields = [
'initiative'
]
通过URL调用的初始序列化程序。
class ChapterFullListSerializer(serializers.ModelSerializer):
url = ChapterUrlHyperlinkedIdentityField("chapter_detail_api", lookup_field='id')
active_initiativeset = serializers.SerializerMethodField('get_active')
school = serializers.CharField(source='school.name', read_only=True)
class Meta:
model = Chapter
fields = [
'url',
'id',
'school',
'name',
'payee',
'active_initiativeset'
]
def get_active(self, chapter):
initiatives = chapter.chapterinitiative_set.filter(active=True)
serializer = ChapterInitiativePartialListSerializer(instance=initiatives, many=True)
return serializer.data
我的代码中应该添加context={'request': request}
?