当我去http://127.0.0.1:8000/movies/
时
它得到错误:djangorestframework :type object has no attribute 'id'
为什么我无法获得id值?
请帮帮我,谢谢!
这是我的代码
serialize.py
class MovieSerializer(serializers.ModelSerializer):
link = serializers.HyperlinkedRelatedField(source='id', view_name='movie_detail')
class Meta:
model = Movie
fields = ( 'link', 'title')
class MovieDetail(object):
queryset = Movie.objects.all()
serializer_class = MovieSerializer
urls.py
urlpatterns = patterns('',
url(r'^movies/$', MovieList.as_view(), name='movie_list'),
url(r'^movies/(?P<pk>[0-9]+)$', MovieDetail.as_view(), name='movie_detail'),
如何编辑它以显示如下结果:
"results": [
{
"link": "http://127.0.0.1:8000/movies/1",
"title": "test",
},
{
"link": "http://127.0.0.1:8000/movies/2",
"title": "test",
},
]
答案 0 :(得分:1)
HyperlinkedRelatedField
必须有source
指向模型上的相关对象。您正在寻找HyperlinkedIdentityField
,它会为当前对象提供一个链接,类似于HyperlinkedModelSerializer
将自动为您执行的操作。
class MovieSerializer(serializers.ModelSerializer):
link = serializers.HyperlinkedIdentityField(view_name='movie_detail')
class Meta:
model = Movie
fields = ( 'link', 'title', )