我使用django rest框架制作API。我只想更改模型中的一个字段,如果我转到特定的网址,则为读取字段
我的模特:
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)
我创建的APis列出了已登录用户的通知。
我要实现的是:
notification/<:id>/markread
notification/<:id>/markunread
如果我转到这个特定的URL,我想修改读取字段..例如,如果标记为未读,则将其设置为None。另外,我还需要检查登录用户是否已收到具有该ID的通知。我知道基本知识以及如何创建网址
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
我最初的尝试是在update_API视图中覆盖put方法
答案 0 :(得分:1)
编写一个简单的函数:
@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)
使用此网址路径:
notifications/<int:pk>/<string:read_status>/
答案 1 :(得分:0)
由于您已经使用DRF
进行编码,为什么不尝试使用viewset
link呢?从前端只需传递带有put请求的更新字段即可。