【发布时间】:2015-06-28 16:25:38
【问题描述】:
所以,我正在尝试将通知模型添加到使用 DRF(Django REST 框架)制作的 API 中,但出现此错误:
AttributeError: 'NotificationQuerySet' object has no attribute 'recipient'
我正在尝试序列化 django 应用模型 Notification。来自这个应用程序:
https://github.com/django-notifications/django-notifications
我的 ViewSet 类是这样的:
class NotificationsViewSet(viewsets.ViewSet):
serializer_class = NotificationsSerializer
def list(self, request):
queryset = Notification.objects.all()
return Response(NotificationsSerializer(queryset).data)
这里是我的序列化器:
class NotificationsSerializer(serializers.ModelSerializer):
class Meta:
model = Notification
fields = ('recipient','description')
depth = 0
因此,当数据传递给序列化器时,它变成“无效”或没有任何数据。 在list方法中做类似的事情:
print queryset[0] 通常返回一个 Notification 对象。但是当把这个queryset传给序列化器的时候,好像是null,而AttributeError就来了。
另外,用控制台试过这个:
notifications = Notification.objects.all()
返回一个 NotificationQuerySet 对象(可迭代)。然后我可以:
for noti in notifications:
print noti
这将输出每个通知的所有 unicode 方法。 对于每个 Notification 实例,我还可以访问模型属性:
for noti in notifications:
print noti.recipient
而且效果很好。
为什么将它传递给序列化程序时不起作用?好奇怪……
【问题讨论】:
标签: python django serialization notifications django-rest-framework