'ListSerializer'对象不可调用

时间:2016-06-01 20:27:07

标签: python django serialization django-rest-framework

我正在尝试使用content_type对象为投票应用程序实现Django-Rest框架。我尝试将rest-framework-generic-relations用于serializers.py。在我看来,错误可能在serializer.py / views.py中,但我是这个框架的新手,非常感谢你的帮助!

views.py:

class vote_detail(generics.RetrieveUpdateDestroyAPIView):
    queryset = VotedItem.objects.all()
    serializer_class = VoteSerializer(queryset, many=True)

serializers.py:

from rest_framework import serializers
from .models import VotedItem
from posts.models import Post
from generic_relations.relations import GenericRelatedField

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = ('title',)

class VoteSerializer(serializers.ModelSerializer):
        """
        A `VotedItem` serializer with a `GenericRelatedField` mapping all possible
        models to their respective serializers.
        """
    voted_object = GenericRelatedField({
        Post: PostSerializer(),
    })

    class Meta:
        model = VotedItem
        fields = ('user', 'voted_object')

和models.py:

from __future__ import unicode_literals

from datetime import datetime

from django.utils.encoding import python_2_unicode_compatible
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.utils import timezone
from django.contrib.auth.models import User
from social_count.managers import VoteManager

SCORES = (
    (+1, '+1'),
    (-1, '-1'),
)

@python_2_unicode_compatible
class VotedItem(models.Model):
    """
    A vote on an object by a User.
    """
    user = models.ForeignKey(User)
    content_type = models.ForeignKey(
        ContentType,
        null=True,
        blank=True,
        on_delete=models.CASCADE,
    )
    object_id = models.PositiveIntegerField(        
        null=True,
    )
    content_object = GenericForeignKey('content_type', 'object_id')
    vote = models.SmallIntegerField(choices=SCORES, blank=True, null=True)
    flag = models.NullBooleanField(blank=True, null=True)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    objects = VoteManager()

    class Meta:
        db_table = 'votes'
        # One vote per user per object
        unique_together = (('user', 'content_type', 'object_id'),)

    def __str__(self):
        return '%s: %s on %s' % (self.user, self.vote, self.content_object)

    def is_upvote(self):
        return self.vote == 1

    def is_downvote(self):
        return self.vote == -1

当我访问www.mypage.com/likes/api/1/时,收到错误消息:

Traceback:

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  149.                     response = self.process_exception_by_middleware(e, request)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  147.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
  58.         return view_func(*args, **kwargs)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  68.             return self.dispatch(request, *args, **kwargs)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  466.             response = self.handle_exception(exc)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  463.             response = handler(request, *args, **kwargs)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/rest_framework/generics.py" in get
  286.         return self.retrieve(request, *args, **kwargs)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/rest_framework/mixins.py" in retrieve
  57.         serializer = self.get_serializer(instance)

File "/home/henry/newpine/src/env/local/lib/python2.7/site-packages/rest_framework/generics.py" in get_serializer
  111.         return serializer_class(*args, **kwargs)

Exception Type: TypeError at /likes/api/1/
Exception Value: 'ListSerializer' object is not callable

1 个答案:

答案 0 :(得分:7)

错误是它试图调用serializer_class,它是ListSerializer的一个实例,而不是clas。

不应该这样:

serializer_class = VoteSerializer(queryset, many=True)

那样:

serializer_class = VoteSerializer