2012-03-16 112 views
0

我有以下模型,我想允許用戶使用django-tastypie以API 加入活動。用django-tastypie添加命令API的最佳方式是什麼?

# Conceptual, may not work. 
class Event(models.Model): 
    title = models.CharField('title', max_length=255) 
    users = models.ForeignKey(User) 

    def join(self, user): 
     self.users.add(user) 
    def leave(self, user): 
     self.users.remove(user) 

# join the events with API like... 
jQuery.post(
    '/api/v1/events/1/join', 
    function(data) { 
     // data should be a joined user instance 
     // or whatever 
     alert(data.username + " has joined."); 
    }, 
); 

但我不知道這樣做的最佳方法。我應該創建EventJoinResource就像

# Conceptual, may not work. 
class EventJoinResource(Resource): 
    action = fields.CharField(attribute='action') 

    def post_detail(self, request, **kwargs): 
     pk = kwargs.get('pk') 
     action = kwargs.get('action') 
     instance = Event.objects.get(pk=pk) 
     getattr(instance, action)(request.user) 

resource = EventJoinResource() 

# ??? I don't know how to write this with django-tastypie urls 
urlpatterns = patterns('', 
    ('r'^api/v1/events/(?P<pk>\d+)/(?P<action>join|leave)/$', include(resource.urls)), 
) 

我該怎麼辦?任何建議,歡迎:-)

回答

1

我想你可以創建「EventResource」。然後,您可以爲加入的用戶,離開的用戶以及任何其他操作提供不同的活動。所以基本上也可能是「EventTypeResource」。

然後每一個事件發生時,您只需將POST到「EventResource」指定事件的類型(通過指定EventTypeResource集合的元素)和任何額外的數據,這樣的:

jQuery.ajax ({ 
    url : '/api/v1/events/', #note the collection URI not the element URI 
    data : { 
     type : '/api/v1/event-types/<pk_of_the_event_type', #URI of EventTypeResource 
     extra_data : { ... } 
    }, 
    success : function(data) { 
     // data should be a joined user instance 
     // or whatever 
     alert(data.username + " has joined."); 
    } 
); 
+0

Sorro我不要用「EventTypeResource」來表達你的意思。有了您的建議,用戶如何加入特定活動?我是否應該像加入「加入」類型和「離開」類型一樣傳遞類型,並更新事件或其他內容? – 2012-03-17 05:42:46

+0

在RESTful API中,不應該有操作或方法調用(這是RPC類API的特徵)。因此,您應該創建一個事件而不是加入它(對其執行操作)。 EventTypeResource可幫助您區分不同的事件,如加入或離開。所以是的,最簡單的形式EventTypeResource可以只有一個屬性「標籤」或「名稱」,並通過ToOneField()與EventResource相關。然後,「用戶加入事件」被表示爲由相關的EventTypeResource「join」創建的EventResource。 – kgr 2012-03-17 09:34:50

+0

我明白了。非常感謝! – 2012-03-18 02:19:37

相關問題