Why my function in Views.py is not correct?

Viewed 21

I have a Notification List view and this function

def mark_as_read(request, notification_id):
    notification = get_object_or_404(Notification.objects.filter(pk=notification_id).exclude(viewed_at__isnull=False))
    notification.viewed_at = datetime.datetime.now()
    notification.save()
    return redirect('users:notification')

It works good but I think it is written not correct? Any body can tell it correct here working get_object_or_404?

1 Answers

It is correct, but you can make it shorter and cleaner with:

notification = get_object_or_404(Notification, pk=notification_id, viewed_at=None)

It is also better to work with the timezone.now function [Django-doc]:

from django.utils.timezone import now

def mark_as_read(request, notification_id):
    notification = get_object_or_404(Notification, pk=notification_id, viewed_at=None)
    notification.viewed_at = now()
    notification.save()
    return redirect('users:notification')

or with the timestamp of the database:

from django.db.models.functions import Now

def mark_as_read(request, notification_id):
    notification = get_object_or_404(Notification, pk=notification_id, viewed_at=None)
    notification.viewed_at = Now()
    notification.save()
    return redirect('users:notification')

The view you are implementing should only be triggered with a POST or PATCH request, not with a GET request, since GET requests are supposed to have no side effects.

Related