0

我正在使用多态模型来设置通知:

我的模型:

class Notification(PolymorphicModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE, default=None, related_name="creatednotifications")
    created_on = models.DateTimeField(default=timezone.now)
    created_for = models.ForeignKey(ElsUser, on_delete=models.CASCADE, default=None, related_name="receivednotifications")
    read = models.DateTimeField(default=None, null=True, blank=True)
    message = models.CharField(default=None, blank=True, null=True, max_length=800)

    @property
    def total(self):
        return self.objects.filter(created_for=self.request.user).count()

    @property
    def unread(self):
        return self.objects.filter(created_for=self.request.user,read=None).count()

    @property
    def read(self):
        return self.objects.filter(created_for=self.request.user).exclude(read=None).count()    

class WorkflowNotification(Notification):
    # permission_transition = models.ForeignKey(WorkflowStatePermissionTransition, on_delete=models.CASCADE)
    action = models.ForeignKey(UserAction, on_delete=models.CASCADE)

目前我只有一个模型 WorkFlowNotification 从多态模型继承,但将来会有很多。

我试图在 API 中获取登录用户的通知计数(总数)..total 作为属性字段给出以提供相同的帮助

我的序列化器:

class NotificationSerializer(serializers.ModelSerializer):
    total = serializers.ReadOnlyField()
    read = serializers.ReadOnlyField()
    unread = serializers.ReadOnlyField()

    class Meta:
        model = Notification
        fields = ['id', 'total','read', 'unread']

在视图中:

   class NotificationsMeta(generics.ListAPIView):
    serializer_class = NotificationSerializer
    queryset = Notification.objects.all()

当我尝试运行服务器时,它显示:

  Got AttributeError when attempting to get a value for field `total` on serializer `NotificationSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `WorkflowNotification` instance.
Original exception text was: Manager isn't accessible via WorkflowNotification instances.
4

2 回答 2

2

既然您只需要“元数据”,那么制作模型序列化器有什么用?或者任何序列化程序,就此而言?序列化器将为您提供模型对象的序列化实例。因此,如果您有多个对象,您将获得多个序列化对象作为响应。

只需将您的视图设为普通APIView 即可。因为没有必要序列化任何东西。

class NotificationsMeta(APIView):
    def get(self, request, format=None):
        qs = Notification.objects.filter(created_for=self.request.user)
        response = {
            'total': qs.count(),
            'read': qs.filter(read=None).count(),
            'unread': qs.exclude(read=None).count()
        }
        return Response(response)

现在从您的模型中删除这些属性函数。

我没有测试您的查询,只是从您的模型中复制它们。您需要检查它们是否正常工作。希望这可以帮助。

于 2019-02-22T07:18:43.083 回答
-1

我不确定如何调用负责在模型中查询的模型属性可以从序列化程序中提供适当的数据。不幸的是,我对此确实存在知识差距。我正在考虑另一种解决方案。我希望以下应该有效。

class NotificationSerializer(serializers.ModelSerializer):
    total = serializers.serializers.SerializerMethodField()

    read = serializers.ReadOnlyField()
    unread = serializers.ReadOnlyField()

    class Meta:
        model = Notification
        fields = ['read', 'unread']


    def get_total(self, obj):
        user =  self.context['request'].user 
        return Notification.objects.filter(created_for=user).count()

如果这项工作有效,那么您也可以为已读和未读做类似的事情。

为了获得 current_user 的通知,我们需要从视图中覆盖 get_queryset。

   class NotificationsMeta(generics.ListAPIView):
    serializer_class = NotificationSerializer
    def get_queryset(self):
       return Notification.objects.filter(created_for=self.request.user)
于 2019-02-22T06:23:31.877 回答