[英]What is the best way to add command api with django-tastypie?
我有以下模型,我想允许用户使用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)),
)
我该怎么办? 任何建议,欢迎:-)
我认为您可以创建“ EventResource”。 然后,对于用户加入,用户离开和任何其他操作,您可能会有不同的事件。 因此,基本上也有“ EventTypeResource”可能会很好。
然后,每次事件发生时,您只需将其张贴到“ 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.");
}
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.