Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django rest serializer.data is an empty OrderedDict()

Here is my model:

from django.db import models
from django.contrib.auth.models import User
from datetime import datetime


class Staff(models.Model):
    employer = models.ForeignKey("shops.Shop")
    user = models.ForeignKey(User)

    def __unicode__(self):
        return self.user.username

Here is my serializer:

from rest_framework import serializers
from staff.models import Staff 


class StaffSerializer(serializers.Serializer):
    class Meta:
        model = Staff
        fields = ("id", "employer", "user")

Here is my view:

from staff.models import Staff
from staff.serializers import StaffSerializer
from rest_framework import  generics
from rest_framework.response import Response



class StaffList(generics.ListCreateAPIView):
    queryset = Staff.objects.all()
    serializer_class = StaffSerializer

    def list(self, request):
        queryset = self.get_queryset()
        serializer = StaffSerializer(queryset, many=True)
        print queryset
        print serializer
        print serializer.data
        return Response(serializer.data)

When viewing this page on the web browsable API this is what I see:

HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS

[
    {}
]

and the result of printing serializer.data and queryset is this:

{<Staff: Alex>}
StaffSerializer([<Staff: Alex>], many=True):
[OrderedDict()]

Is there something wrong with my serializer or is this another issue all together?

like image 493
Danny Avatar asked Apr 05 '15 12:04

Danny


1 Answers

You need to use serializers.ModelSerializer not a serializers.Serializer if you are working with models and querysets.

If you are using serializers.Serializer you need to define field in it manually. Like this:

class StaffSerializer(serializers.Serializer):
  id = serializers.IntegerField()
  content = serializers.CharField(max_length=200)

etc. You cant reference them in meta like with ModelSerializer. Docs on ModelSerializer can be found here

like image 112
Aldarund Avatar answered Oct 29 '22 18:10

Aldarund