Change model field if requested particular url

69 Views Asked by At

Im making API using django rest framework . I only want to change one field in model which is the read field if i go to a particular url

my model:

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)

The APis i made lists the notifications for a logged in user.

What i want to implement is that :

notification/<:id>/markread

notification/<:id>/markunread

If i go to this particular url i want to modify the read field ..For example make it None if to mark unread. Also i need to check if the logged in user has received the notification with that id.I know the basics and how to create the urls

class NotificationMarkRead(generics.UpdateAPIView):
    serializer_class = NotificationSerializer

    def get_queryset(self):
        queryset =  Notification.objects.filter(created_for=self.request.user)

        return queryset 

class NotificationMarkUnread(generics.UpdateAPIView):
    serializer_class = NotificationSerializer

    def get_queryset(self):
        queryset =  Notification.objects.filter(created_for=self.request.user)

        return queryset 

    def update

My initial try is to override the put method in update_API view

2

There are 2 best solutions below

1
On BEST ANSWER

Write a simple function:

@api_view(['PUT'])
def notification_toggle_read_status(request, pk, read_status):
    notification = Notification.objects.get(pk=pk)
    if read_status == 'markread':
        notification.read = timezone.now()
    else:
        notification.read = None
    notification.save(update_fields=['read'])
    serializer = NotificationSerializer(instance=notification)
    return Response(serializer.data)

use this url path:

notifications/<int:pk>/<string:read_status>/

2
On

As you have already coding with DRF why not try with viewset link . And from front-end just pass update fields with put request.