【问题标题】:How to prevent update a column in Tastypie如何防止更新 Tastypie 中的列
【发布时间】:2018-12-29 03:07:19
【问题描述】:
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 = "don't update me"。

为什么用空字符串''更新它?

【问题讨论】:

    标签: django tastypie


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2020-05-15
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多