这是我的模特:
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
这是我的序列化器:
from rest_framework import serializers
from staff.models import Staff
class StaffSerializer(serializers.Serializer):
class Meta:
model = Staff
fields = ("id", "employer", "user")
以下是我的观点:
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)
在网络浏览API上查看此页面时,我看到了这一点:
HTTP 200 OK
Content-Type: application/json
Vary: Accept
Allow: GET, POST, HEAD, OPTIONS
[
{}
]
打印serializer.data和queryset的结果如下:
{<Staff: Alex>}
StaffSerializer([<Staff: Alex>], many=True):
[OrderedDict()]
我的序列化程序是否有问题,或者这是另一个问题吗?
答案 0 :(得分:26)
如果您使用的是模型和查询集,则需要使用 serializers.ModelSerializer 而不是 serializers.Serializer 。
如果您正在使用serializers.Serializer,您需要手动定义其中的字段。像这样:
class StaffSerializer(serializers.Serializer):
id = serializers.IntegerField()
content = serializers.CharField(max_length=200)
等。 你不能像在ModelSerializer中那样在meta中引用它们。可以找到ModelSerializer上的文档here