Django ModelViewSet PATCH请求返回模型字段已更新

时间:2018-11-20 04:50:07

标签: django django-rest-framework

class MerchantStampCardViewSet(viewsets.ModelViewSet):
    '''
    A view set for listing/retrieving/updating/deleting stamp cards for the current
    merchant
    '''
        permission_classes = (IsMerchantAndAuthenticated, )

def get_queryset(self):
    if len(MerchantProfile.objects.filter(user=self.request.user)) > 0:
        merchant_profile = MerchantProfile.objects.get(user=self.request.user)
        if merchant_profile.merchant:
            return StampCard.objects.filter(merchant=merchant_profile.merchant)
    return None

def get_serializer_class(self):
    if self.request.method == 'GET':
        return StampCardSerializerWithRewards
    else:
        return StampCardSerializer

我正在尝试使此代码返回响应正文中更改的字段。该模型类具有几个字段,例如名称,城市,省,邮政编码和地址,并且通过前端,用户一次只能更改一个字段,但是我希望200响应的正文包含更改的字段名称,并且新值只是为了确认更改成功并且没有出错。

例如,如果用户将名称更改为Billy。响应应为200,并且正文应显示{name:'Billy'}

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以尝试这样:

class YourViewSet(...):

  def update(self, request, *args, **kwargs):
    instance = self.get_object()
    current_data = self.get_serializer(instance).data  # collect current data
    # next few lines of the code is from default implementation
    serializer = self.get_serializer(instance, data=request.data, partial=partial)
    serializer.is_valid(raise_exception=True)
    self.perform_update(serializer)
    if getattr(instance, '_prefetched_objects_cache', None):
        instance._prefetched_objects_cache = {}

    updated_data = serializer.data  # now we get the updated data
    response_dict = dict()
    for key, value in current_data:
         # find the differences
         if updated_data.get(key) != value:
            response_dict[key] = updated_data.get(key)
    return Response(response_dict)  # send the difference through response

在这里,我对更新方法进行了覆盖。然后,我从当前对象和更新的对象中收集了字典数据。然后比较它们,并在字典中发送差异作为响应。 仅供参考,这是未经测试的代码。