我正在使用rest_framework库构建一个django restful json API,但是当我向它提交请求时它会返回空的json [],即使数据库表中有大量记录。这是'我的代码
models.py
class Member(models.Model):
email = models.EmailField()
mobile = models.CharField(max_length=11, null=False)
username = models.CharField(max_length=20, null= False, help_text="Username")
password = models.CharField(max_length=15, null=False, help_text="Password")
mobile_id = models.CharField(max_length=100, null=True, blank=True)
joined_date = models.DateTimeField(auto_now_add=True)
serializers.py
class MemberSerializer(serializers.Serializer):
class Meta:
model = Member
fields = ('email', 'mobile', 'username', 'joined_date')
views.py
class MemberAPI(viewsets.ModelViewSet):
serializer_class = MemberSerializer
queryset = Member.objects.all()
urls.py
router = DefaultRouter()
router.register(r'member', MemberAPI, base_name='member')
urlpatterns = router.urls
答案 0 :(得分:5)
我现在明白了。看来,我正在继承一个基类泛型类的序列化 的 serializers.py 强>
我应该像这样继承ModelSerializer
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = ('email', 'mobile', 'username', 'joined_date')