为什么我在Views.py中的函数不正确



我有一个通知列表视图和这个函数

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')

它很好用,但我认为它写得不对?在get_object_or_404工作时,任何人都能告诉它正确吗?

这是正确的,但您可以使用使其更短、更干净

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

最好使用timezone.now函数[Django-doc]:

from django.utils.timezone importnow
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')

或与数据库的时间戳:

from django.db.models.functions importNow
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')

您正在实现的视图应该只通过POST或PATCH请求触发,而不是通过GET请求触发,因为GET请求应该没有副作用。

最新更新