Django REST - 异常断言:`fields`必须为列表或元组

2024-10-02 10:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当使用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

我的设置是。。。。在

设置.py

^{pr2}$

视图

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

网址.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)

有什么想法吗?在


Tags: djangofrompyimportrestfieldsmodelsframework
2条回答

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

fields = ('test', )

没有逗号fields = ('test')实际上相当于fields = 'test'。在

来自docs

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

('test')不是元组,它只是'test'的{a1}值。在

应添加尾随逗号以创建单例元组:

fields = ('test',)

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

^{pr2}$

相关问题 更多 >

    热门问题