Django rest framework 如果请求特定url,请更改模型字段
我正在使用django rest框架制作API。我只想更改模型中的一个字段,如果我转到一个特定的url,它就是read字段 我的模型:Django rest framework 如果请求特定url,请更改模型字段,django-rest-framework,django-polymorphic,Django Rest Framework,Django Polymorphic,我正在使用django rest框架制作API。我只想更改模型中的一个字段,如果我转到一个特定的url,它就是read字段 我的模型: class Notification(PolymorphicModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_by = models.ForeignKey(ElsUser, on_delete=models.CAS
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)
我制作的API列出了登录用户的通知
我想实现的是:
notification/<:id>/markread
notification/<:id>/markunread
我最初的尝试是重写update_API视图中的put方法,编写一个简单的函数:
@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)
使用此url路径:
notifications////code>既然您已经用DRF
编码了,为什么不试试viewset
。从前端只需通过put请求传递更新字段 使用视图集而不是常规视图的优点是什么?您最好先了解一下,我使用了与put方法的notifications/id相同的url。。。将所有其他字段设置为只读字段
@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)