如何防止在Tastypie中更新列

时间:2018-07-20 18:47:49

标签: django tastypie

class Hello(models.Model):
  name = models.CharField(max_length=8,  blank=True)
  column_create_no_update = models.CharField(max_length=8,  blank=True)



class HelloResource(ModelResource):

  def dehydrate(self, bundle):

    if (bundle.request.META['REQUEST_METHOD'] == 'PUT') and ('column_create_no_update' in bundle.data.keys()):
      del bundle.data['column_create_no_update']

    return bundle

1)创建一条记录

createData['name'] = 'foo name';
createData['column_create_no_update'] = "don't update me";

Ajax POST在db中创建一条记录。

2)使用ajax调用更新表时,

updateData['name'] = 'foo name updated';  

Ajax PUT更新记录。更新中未提供“ column_create_no_update”。

我在函数dehydrate()中注意到,bundle.data ['column_create_no_update'] =''和bundle.data ['column_create_no_update']被删除。 返回“ bundle”后,删除后仅存在bundle.data ['name']。

但是,在数据库中,“ column_create_no_update”已更新为“”。我希望保留它:column_create_no_update =“不要更新我”。

为什么使用空字符串“”更新它?

1 个答案:

答案 0 :(得分:1)

您可以在您的类中覆盖update_in_place方法。此方法的主要功能是仅针对PUT请求使用新数据更新旧数据,因此您无需为请求方法添加其他检查。 您可以在https://github.com/django-tastypie/django-tastypie/blob/6721e373de802648ce0fad61d15c07fc01422182/tastypie/resources.py#L1714

中找到好吃的代码
class Hello(models.Model):

    name = models.CharField(max_length=8,  blank=True)
    column_create_no_update = models.CharField(max_length=8,  blank=True)


class HelloResource(ModelResource):

    def update_in_place(self, request, original_bundle, new_data):    
        if ('column_create_no_update' in new_data.keys()):
            del new_data['column_create_no_update']

        return super(HelloResource, self).update_in_place(request, original_bundle, new_data)