Python int()参数必须是字符串或数字,而不是';选择';

Python int()参数必须是字符串或数字,而不是';选择';,python,django,python-2.7,django-rest-framework,django-1.10,Python,Django,Python 2.7,Django Rest Framework,Django 1.10,int()参数必须是字符串或数字,而不是“Choice” 我是django rest框架的新手 请帮忙 这是我的serializers.py class VoteSerializer(ModelSerializer): class Meta: model=Vote fields='__all__' def from_native(self, data, files): data['poll_id'] = self.context[

int()参数必须是字符串或数字,而不是“Choice”
我是django rest框架的新手 请帮忙

这是我的serializers.py

class VoteSerializer(ModelSerializer):
    class Meta:
        model=Vote
        fields='__all__'

    def from_native(self, data, files):
        data['poll_id'] = self.context['pollid']
        return super(VoteSerializer, self).from_native(data, files)

    def validate(self, data):
        choice=data.get("choice",None)
        user=data.get("id",None)
        polid=data.get("poll_id")
        if not user and not choice:
            raise ValidationError("A user and choice has to be present")

        choice_poll_obj=Choice.objects.filter(
            Q(id=choice) |
            Q(poll=polid)
        ).distinct()

        user_obj=User.objects.get(id=user)
        if user_obj.exists() and choice_poll_obj.exists():
            pass
        else:
            raise ValidationError("This choice/user is not valid for this question")

        return data
这是我的观点

class VotesAPIView (CreateAPIView) :
    serializer_class = VoteSerializer

    def post(self, request, *args, **kwargs):
        data = request.data  # like request.post
        poll = Poll.objects.get(id=kwargs['pk'])
        poll_id=poll.id
        serializer = VoteSerializer(data=request.data,context={'pollid': poll_id})
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
这是我代码的回溯。请调查一下:

    Environment:


Request Method: POST
Request URL: http://localhost/pollsAPI/1/vote

Django Version: 1.10.5
Python Version: 2.7.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rest_framework',
 'polls.apps.PollsConfig']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

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

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

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  483.             response = self.handle_exception(exc)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception
  443.             self.raise_uncaught_exception(exc)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
  480.             response = handler(request, *args, **kwargs)

File "/home/yodaplus/Documents/RESTAPIs/polls/views.py" in post
  94.         if serializer.is_valid(raise_exception=True):

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/rest_framework/serializers.py" in is_valid
  236.                 self._validated_data = self.run_validation(self.initial_data)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/rest_framework/serializers.py" in run_validation
  434.             value = self.validate(value)

File "/home/yodaplus/Documents/RESTAPIs/polls/serializers.py" in validate
  123.                 Q(poll=polid)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/query.py" in filter
  796.         return self._filter_or_exclude(False, *args, **kwargs)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude
  814.             clone.query.add_q(Q(*args, **kwargs))

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q
  1227.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1247.                     current_negated, allow_joins, split_subq)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in _add_q
  1253.                     allow_joins=allow_joins, split_subq=split_subq,

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_filter
  1187.             condition = self.build_lookup(lookups, col, value)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/sql/query.py" in build_lookup
  1083.                 return final_lookup(lhs, rhs)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/lookups.py" in __init__
  19.         self.rhs = self.get_prep_lookup()

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/lookups.py" in get_prep_lookup
  59.             return self.lhs.output_field.get_prep_value(self.rhs)

File "/home/yodaplus/Documents/env_rest/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py" in get_prep_value
  946.         return int(value)

Exception Type: TypeError at /pollsAPI/1/vote
Exception Value: int() argument must be a string or a number, not 'Choice'
也许应该是这样

choice_poll_obj=Choice.objects.filter(
        Q(id=choice) |
        Q(poll_id=polid)  # <- use poll_id instead of poll
    ).distinct()
choice\u poll\u obj=choice.objects.filter(
Q(id=选择)|

Q(poll_id=polid)#它应该是poll双下划线id

choice_poll_obj=Choice.objects.filter(
        Q(id=choice) |
        Q(poll__id=polid) 
    ).distinct()

请包括回溯。@Sayse添加了回溯我已回滚您上次编辑的内容,因为您删除的回溯实际上是最重要的部分question@Anup请提供打印输出(类型(polid))
在您的
validate
方法中。输出是一个对象轮询。因此,我获取了id,它给了我一个整数。仍然显示相同的错误得到了答案。正如您所说,我正在将整数与对象进行比较。纠正了它并解决了问题。感谢您为我指路。