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)),
)
我該怎麼辦?任何建議,歡迎:-)
Sorro我不要用「EventTypeResource」來表達你的意思。有了您的建議,用戶如何加入特定活動?我是否應該像加入「加入」類型和「離開」類型一樣傳遞類型,並更新事件或其他內容? – 2012-03-17 05:42:46
在RESTful API中,不應該有操作或方法調用(這是RPC類API的特徵)。因此,您應該創建一個事件而不是加入它(對其執行操作)。 EventTypeResource可幫助您區分不同的事件,如加入或離開。所以是的,最簡單的形式EventTypeResource可以只有一個屬性「標籤」或「名稱」,並通過ToOneField()與EventResource相關。然後,「用戶加入事件」被表示爲由相關的EventTypeResource「join」創建的EventResource。 – kgr 2012-03-17 09:34:50
我明白了。非常感謝! – 2012-03-18 02:19:37