2013-01-31 54 views
1

我可以在哪裏放置自定義邏輯,或者我應該重載哪個函數以在tastypie中添加自定義邏輯。例如:要返回CustomObject,其中包含大寫的name,但在返回之前,我想使其小寫。tastypie中的自定義邏輯

回答

1

如果你想提供這樣的自定義的東西,我建議在dehydrate期間這樣做。退房documentation,這個例子相當多,你要查找的內容:

class MyResource(ModelResource): 
    # The ``title`` field is already added to the class by ``ModelResource`` 
    # and populated off ``Note.title``. But we want allcaps titles... 

    class Meta: 
     queryset = Note.objects.all() 

    def dehydrate_title(self, bundle): 
     return bundle.data['title'].upper() 

嗯,除了你要找的當然:)的.lower()

class CustomObjectResource(ModelResource): 

    class Meta: 
     queryset = CustomObject.objects.all() 

    def dehydrate_title(self, bundle): 
     return bundle.data['name'].lower() 
+0

謝謝@msc,也許這是我提出問題的失敗。我想要的是重寫獲取,張貼,放置行爲。舉個例子,當用戶發送查詢到'get'時,我會增加這個對象的計數器,當用戶發送'post'查詢時,首先我將檢查特殊權限,然後給出訪問權限來更改一些數據 – user1318496

+1

對於get,這也可以在脫水循環中完成,檢查脫水()。 http://django-tastypie.readthedocs.org/en/latest/resources.html#advanced-data-preparation – msc

+0

用於放置,發佈並獲取使用apply_authorization_limits()進行訪問 – msc

0

您可以恕我直言,覆蓋所有領域:

class CustomResource(ModelResource): 

    name = fields.CharField(
     attribute='get_lowercased_name', 
     readonly=True 
    ) 

    class Meta: 
     queryset = Custom.objects.all() 

而且你需要在你的Custom模型類中定義的方法get_lowercased_name

+0

感謝@Michal以上才被提供例子,似乎不是很好的例子,因爲使用標準API解決。我想要的是在返回數據之前做一些邏輯,但我不知道我可以在哪裏放置該邏輯。 – user1318496