all()在Django中得到了一个意外的关键字参数'pk'

时间:2014-10-13 13:30:14

标签: python django rest

我遇到了Django和Django REST框架的问题。

当我转到http://mynameislee.co.uk/albums/时它工作正常并且返回Django Framework很好但是当我尝试http://mynameislee.co.uk/albums/1时,我得到all()得到一个意外的关键字参数'pk'。

这是我的代码。

urls.py

# API
url(r'^albums/$', 'canary.views.album_list', name='album_list'),
url(r'^albums/(?P<pk>[0-9])$', 'canary.views.album_detail', name='album_detail'),

views.py

@login_required
@api_view(['GET', 'POST'])
def album_list(request):

# List all tasks, or create a new task.

if request.method == 'GET':
    album = Album.objects.all()
    serializer = AlbumSerializer(album, many=True)
    return Response(serializer.data)

elif request.method == 'POST':
    serializer = AlbumSerializer(data=request.DATA)
if serializer.is_valid():
   serializer.save()
   return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
  return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@login_required
@api_view(['GET', 'PUT', 'DELETE'])
def album_detail(request, pk):

# Get, update or delete a specific album

try:
  album = Album.objects.all(pk=id)
except Album.DoesNotExist:
  return Response(status=status.HTTP_404_NOT_FOUND)

if request.method == 'GET':
  serializer = AlbumSerializer(album)
  return Response(serializer.data)

elif request.method == 'PUT':
  serializer = AlbumSerializer(album, data=request.DATA)
  if serializer.is_valid():
    serializer.save()
  return Response(serializer.data)
else:
  return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

elif request.method == 'DELETE':
  album.delete()
  return Response(status=status.HTTP_204_NO_CONTENT)

models.py

class Album(models.Model):

  album_id = models.AutoField(primary_key=True)
  artist_name = models.CharField(max_length=255, blank=True)
  album_name = models.CharField(max_length=255, blank=True)

  def __unicode__(self):
       return self.album_name

2 个答案:

答案 0 :(得分:4)

您无法将all与过滤器设置一起使用。

album = Album.objects.all(pk=id) #wrong

改为使用filter

album = Album.objects.filter(pk=id)
>>> type(album) -> 'QuerySet'

以下是docs,其中有很多例子。

正如@Bjorn建议的那样:你也可以使用get来保存你从查询集中获取项目:

album = Album.objects.get(pk=id)
>>> type(album) -> 'Album'

答案 1 :(得分:2)

我想你想要

album = Album.objects.filter(pk=id)

而不是

album = Album.objects.all(pk=id)