多态模型序列化器

Polymorphic models serializer

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

我的模特:

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 中已登录用户的通知计数(总数).. 总数作为 属性 字段给出以帮助相同

我的序列化器:

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.

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

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)

既然你只需要'meta data',那么做一个模型序列化器有什么用呢?或者任何序列化程序,就此而言?序列化程序将为您提供模型对象的序列化实例。所以如果你有多个对象,你会得到多个序列化的对象作为响应。

将您的视图设为正常 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)

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

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