我想创建一个many-to-many
关系,其中一个人可以在许多俱乐部,一个俱乐部可以有很多人。我为以下逻辑添加了models.py
和serializers.py
但是当我尝试在命令提示符中对其进行序列化时,我收到以下错误 - 我在这里做错了什么?我甚至没有HyperlinkedIdentityField
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 503, in data
ret = super(Serializer, self).data
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 239, in data
self._data = self.to_representation(self.instance)
File "C:\Users\user\corr\lib\site-packages\rest_framework\serializers.py", line 472, in to_representation
ret[field.field_name] = field.to_representation(attribute)
File "C:\Users\user\corr\lib\site-packages\rest_framework\relations.py", line 320, in to_representation"the serializer." % self.__class__.__name__
AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.
models.py
class Club(models.Model):
club_name = models.CharField(default='',blank=False,max_length=100)
class Person(models.Model):
person_name = models.CharField(default='',blank=False,max_length=200)
clubs = models.ManyToManyField(Club)
serializers.py
class ClubSerializer(serializers.ModelSerializer):
class Meta:
model = Club
fields = ('url','id','club_name','person')
class PersonSerializer(serializers.ModelSerializer):
clubs = ClubSerializer()
class Meta:
model = Person
fields = ('url','id','person_name','clubs')
views.py
class ClubDetail(generics.ListCreateAPIView):
serializer_class = ClubSerializer
def get_queryset(self):
club = Clubs.objects.get(pk=self.kwargs.get('pk',None))
persons = Person.objects.filter(club=club)
return persons
class ClubList(generics.ListCreateAPIView):
queryset = Club.objects.all()
serializer_class = ClubSerializer
class PersonDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = PersonSerializer
def get_object(self):
person_id = self.kwargs.get('pk',None)
return Person.objects.get(pk=person_id)
检查创建的序列化器给我这个 -
PersonSerializer(<Person: fd>):
url = HyperlinkedIdentityField(view_name='person-detail')
id = IntegerField(label='ID', read_only=True)
person_name = CharField(max_length=200, required=False)
clubs = ClubSerializer():
url = HyperlinkedIdentityField(view_name='club-detail')
id = IntegerField(label='ID', read_only=True)
club_name = CharField(max_length=100, required=False)
但是serializer.data
给了我错误
******************编辑*********************
我意识到错误可能是因为url
模式,所以我添加了以下网址模式,但我仍然收到错误 -
urlpatterns = format_suffix_patterns([
url(r'^$', views.api_root),
url(r'^clubs/$',
views.ClubList.as_view(),
name='club-list'),
url(r'^clubs/(?P<pk>[0-9]+)/persons/$',
views.ClubDetail.as_view(),
name='club-detail'),
url(r'^person/(?P<pk>[0-9]+)/$',
views.PersonDetail.as_view(),
name='person-detail'),
])
答案 0 :(得分:30)
由于HyperlinkedIdentityField
希望在序列化程序的request
中收到context
,因此可以构建绝对网址,因此您收到此错误。当您在命令行上初始化序列化程序时,您无法访问请求,因此会收到错误。
如果您需要在命令行上检查序列化程序,则需要执行以下操作:
from rest_framework.request import Request
from rest_framework.test import APIRequestFactory
from .models import Person
from .serializers import PersonSerializer
factory = APIRequestFactory()
request = factory.get('/')
serializer_context = {
'request': Request(request),
}
p = Person.objects.first()
s = PersonSerializer(instance=p, context=serializer_context)
print s.data
您的网址字段看起来像http://testserver/person/1/
。
答案 1 :(得分:15)
我有两个解决方案......
urls.py
<强> 1)强> 如果您使用的是router.register,则可以添加 base_name :
router.register(r'users', views.UserViewSet, base_name='users')
urlpatterns = [
url(r'', include(router.urls)),
]
<强> 2)强> 如果您有这样的事情:
urlpatterns = [
url(r'^user/$', views.UserRequestViewSet.as_view()),
]
您必须将上下文传递给序列化程序:
views.py
class UserRequestViewSet(APIView):
def get(self, request, pk=None, format=None):
user = ...
serializer_context = {
'request': request,
}
serializer = api_serializers.UserSerializer(user, context=serializer_context)
return Response(serializer.data)
像这样,您可以继续使用序列化程序上的网址: serializers.py
...
url = serializers.HyperlinkedIdentityField(view_name="user")
...
答案 2 :(得分:7)
我遇到了同样的问题。我的方法是删除&#39; url&#39;来自serializer.py中的Meta.fields。
答案 3 :(得分:4)
根据Slipstream的回答,我编辑了views.py
介绍上下文,现在它可以正常工作。
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = User.objects.all().select_related('profile').order_by('-date_joined')
serializer_class = UserSerializer
@list_route(methods=['get'], url_path='username/(?P<username>\w+)')
def getByUsername(self, request, username):
serializer_context = {
'request': request,
}
user = get_object_or_404(User, username=username)
return Response(UserSerializer(user, context=serializer_context).data, status=status.HTTP_200_OK)
答案 4 :(得分:1)
在MDT响应之后,我使用django-rest-framework,并通过将request更改为request._request来解决它。
serializer_context = {'request': Request(request._request)}
答案 5 :(得分:1)
您可以通过将实例化(在views.py中)更改为类似这样的方式来解决它:
your_serializer = YourModelSerializer(YourQuerySet_or_object, many=True,context={'request':request})
答案 6 :(得分:0)
在只需要相对URL的情况下,只需将None
传递到'request'
中的context
键即可。在命令行中测试序列化器。
serializer = YourModelSerializer(modelInstance_or_obj, context={'request': None})
答案 7 :(得分:0)
对于外部网址,您可以简单地将请求置于无:
context={
'request': None
},