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?
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
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