Tu Le Thanh
Tu Le Thanh

Reputation: 671

How to get instance of model in UpdateAPIView django REST?

I have a model Request is below

class Request(models.Model):
    PENDING = 1
    APPROVE = 2
    REJECT = 3
    STATUS_CHOICES = (
        (PENDING, 'Pending'),
        (APPROVE, 'Approve'),
        (REJECT, 'Reject')
    )
    seller = models.ForeignKey(
        Seller,
        on_delete=models.CASCADE,
        related_name='requests',
    )
    owner = models.OneToOneField(
        UserProfile,
        on_delete=models.CASCADE,
        related_name='request',
    )
    reject_reason = models.TextField(default='')
    status = models.PositiveSmallIntegerField(STATUS_CHOICES, default=1)
    created_at = models.DateField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

And an UpdateAPIView

class RequestDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Request.objects.all()
    serializer_class = RequestUpdateSerializer
    permission_classes = (IsAuthenticated, IsAdminOrRequestOwner)
    name = 'request-detail'

    # TODO: send an email inform user that the request have been approve or reject
    def update(self, request, *args, **kwargs):
        if self.request.user.profile.role != 3:
            raise serializers.ValidationError(
                {'detail': 'You do not have permission to perform this action'})

        return super().update(request, *args, **kwargs)

What I need is to send an email to the owner of that Request instance. I have written a function to do that but it has to be called in update() method of UpdateAPIView

In order to send an email, it required the data from the Request instance that is being updated. The request data only contains information about status

My question is what is the proper way to get the Request instance inside the UpdateAPIView. My approach is to get the id from kwargs params and then query the Request instance that I needed.

Upvotes: 3

Views: 1440

Answers (1)

Ersain
Ersain

Reputation: 1520

Use a get_object method:

def update(self, request, *args, **kwargs):
    # some logic

    instance = self.get_object()
    send_email(to=instance.owner.email, message='Your message')  # use your own send_email

    return super().update(request, *args, **kwargs)

Upvotes: 4

Related Questions