When querying Django via REST using the Django REST framework I get the error,
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
My settings are....
settings.py
THIRD_PARTY_APPS = (
'south', # Database migration helpers:
'crispy_forms', # Form layouts
'rest_framework',
)
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.AllowAny',
)
}
views
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')),
)
Serializers
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',)
Models
from django.db import models
class Abc(models.Model):
test = models.CharField(max_length=12)
Any ideas ?
You need to use a tuple or list for fields
, to represent a tuple with single item you need to use a trailing comma:
fields = ('test', )
Without a comma fields = ('test')
is actually equivalent to fields = 'test'
.
From 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')
is not a tuple, it is the same value as simply 'test'
.
You should add a trailing comma to create a singleton tuple:
fields = ('test',)
Or you can use a list and don't bother about the commas:
fields = ['test']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With