【问题标题】:Django Tastypie hidden PKDjango Tastypie隐藏PK
【发布时间】:2015-08-16 20:12:54
【问题描述】:

我正在使用最新的 Tastypie,但遇到了问题。我需要隐藏 PK,这样人​​们就看不到服务增长。所有型号都有UUIDField。我正在使用 detail_uri_name 字段,它为我提供了 uuid 而不是 ID/PK 来获取请求,所以到目前为止一切都很好。

我遇到的问题是当我去PUTPATCHresource_uri 时。它认为它是一个没有 ID 的新资源,因此我在尝试创建新记录时遇到重复的键错误。有任何想法吗?这是我的资源。

class UserResource(ModelResource):

    class Meta:
       detail_uri_name='uuid'
       queryset = User.objects.all()
       resource_name = 'user'
       always_return_data = True
       authentication = SessionAuthentication() 
       authorization = Authorization()
       excludes=['id', 'password', 'created', 'approved', 'password_reset_code', 'password_reset_datetime']

    def prepend_urls(self):
        return [
            url(r'^(?P<resource_name>%s)/(?P<uuid>[\w\.-]+)/$' % self._meta.resource_name, self.wrap_view('dispatch_detail'), name='api_dispatch_detail'),
        ]

【问题讨论】:

    标签: python django django-models tastypie


    【解决方案1】:

    您最好将模型的 pk 更改为随机哈希。 Here is an app 就是这样做的:

    A new base class for Django models, which provides them with a better
    and random looking primary key for the 'id' field.
    
    This solves the problem of having predictable, sequentially numbered
    primary keys for Django models.
    
    Just use 'RandomPrimaryIdModel' as base class for your Django models.
    They will then automatically get those new, random looking IDs.
    
    
    The generated keys look similar to what you know from URL shorteners.
    Here are some examples:
    
        Ada6z
        UFLX1
        Q68mf
        zjvsx3
        fDXshK
        VNuL0Lp
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-23
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      • 2012-04-11
      • 2013-05-29
      相关资源
      最近更新 更多