Django REST - AssertionError:`fields`必须是列表或元组

时间:2014-01-29 12:55:43

标签: python django-rest-framework

使用Django REST框架通过REST查询Django时出现错误,

  File "/folder/pythonenv/project/lib/python2.7/site-packages/rest_framework/serializers.py", line 241, in get_fields
    assert isinstance(self.opts.fields, (list, tuple)), '`fields` must be a list or tuple'
AssertionError: `fields` must be a list or tuple

我的设置是......

settings.py

THIRD_PARTY_APPS = (
        'south',  # Database migration helpers:
        'crispy_forms',  # Form layouts
        'rest_framework',
    )

REST_FRAMEWORK = {
                'DEFAULT_PERMISSION_CLASSES': (
                    'rest_framework.permissions.AllowAny',
                )
    }

视图

from django.shortcuts import render
from rest_framework import viewsets
from quickstart.serializers import from quickstart.serializers import TicketInputSerializer
from models import Abc

class TicketInputViewSet(viewsets.ModelViewSet):
    queryset = Abc.objects.all()
    serializer_class = TicketInputSerializer

urls.py

router = routers.DefaultRouter()
router.register(r'ticket', views.TicketViewSet)

urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    url(r'^test', include('rest_framework.urls', namespace='rest_framework')),

) 

串行器

from models import Abc
from django.contrib.auth.models import User, Group
from rest_framework import serializers

class TicketInputSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Abc
        fields = ('test',)

模型

from django.db import models

class Abc(models.Model):
    test = models.CharField(max_length=12)

有什么想法吗?

2 个答案:

答案 0 :(得分:16)

您需要使用fields的元组或列表来表示您需要使用尾随逗号的单个项目的元组:

fields = ('test', )

没有逗号fields = ('test')实际上等同于fields = 'test'

来自docs

  

一个特殊问题是构造包含0或1的元组   items:语法有一些额外的怪癖来容纳这些。空   元组是由一对空括号构成的;一个元组   通过使用逗号跟随值来构造一个项目(它不是   足以将一个值括在括号中)。丑,但是   有效的。

答案 1 :(得分:6)

('test')不是元组,same值仅为'test'

您应该添加一个尾随逗号来创建一个单例元组:

fields = ('test',)

或者您可以使用列表而不用担心逗号:

fields = ['test']