我在哪里可以在RetrieveAPIView中编写查询后逻辑?

时间:2017-12-15 04:37:55

标签: python django django-rest-framework

我在哪里可以在RetrieveAPIView中编写查询后逻辑?

在我的models.py中,我有一个Message类:

upload_max_filesize=100M

在views.py中:

class Message(models.Model):
    """
    message
    """
    message_num = models.CharField(default=getMessageNum, max_length=16)  

    title = models.CharField(max_length=64)
    content = models.CharField(max_length=1024)

    is_read = models.DateTimeField(null=True, blank=True)

    create_user = models.ForeignKey(User, related_name="created_messages")
    receive_user = models.ManyToManyField(User, related_name="received_messages")

    ctime = models.DateTimeField(auto_now_add=True)
    uptime = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

您可以在# the message list class UserMessageListAPIView(ListAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages # the message detail class UserMessageRetrieveAPIView(RetrieveAPIView): serializer_class = UserMessageSerializer permission_classes = [] def get_queryset(self): user = self.request.user messages = user.received_messages.all() return messages 中看到我可以检索邮件实例。 如何设置消息UserMessageRetrieveAPIView的逻辑?我可以在哪里设置它?

修改

我的意思是,如果可能,我想获取检索到的信息,然后更新它,但我不知道如何获得它。

1 个答案:

答案 0 :(得分:0)

class UserMessageRetrieveAPIView(RetrieveAPIView):
    serializer_class = UserMessageSerializer
    permission_classes = []

    def get_queryset(self):
        user = self.request.user
        messages = user.received_messages.all()

        return messages

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_read = true
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)