Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 'str' object has no attribute 'values' in rest_framework

When I use rest_framework to implement the api

models.py:

class Store(models.Model):

    name = models.CharField(max_length=20)

    notes = models.TextField(blank=True, default='')

    def __str__(self):

        return self.name

myapp/api.py:

class StoreSerializer(serializers.ModelSerializer):

    class Meta:

        model = Store

class StoreViewSet(viewsets.ModelViewSet):

    queryset = Store.objects.all()

    serializer_class = StoreSerializer

    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

project/api.py

v1 = routers.DefaultRouter()
v1.register('store',StoreViewSet)
v1.register('stores/menu_item',MenuItemViewSet)

urls.py

    from .api import v1

    urlpatterns = [

    url(r'^api/v1/', include(v1.urls)),

    ]

I met the following traceback

AssertionError at /api/v1/store/ ("Creating a ModelSerializer without either the 'fields' attribute or the 'exclude' attribute has been deprecated since 3.3.0, and is now disallowed. Add an explicit fields = 'all' to the StoreSerializer serializer.",)

So I add the fields = '__all__' to fix this error

class StoreSerializer(serializers.ModelSerializer):

   fields = '__all__'

   class Meta:
       model = Store

But next I met this traceback

Based on that traceback I don't know which part is missing.

like image 926
Jonathan Cheng Avatar asked Jul 30 '17 09:07

Jonathan Cheng


1 Answers

Put it inside Meta:

class StoreSerializer(serializers.ModelSerializer):

    class Meta:
        model = Store
        fields = '__all__'

specifying-fields

like image 189
Brown Bear Avatar answered Sep 20 '22 06:09

Brown Bear