0

私は次のモデルを持っており、ユーザーが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)),
)

私は何をすべきか?任意の提案を歓迎します:-)

4

1 に答える 1

1

「EventResource」を作成できると思います。次に、参加するユーザー、離脱するユーザー、およびその他のアクションに対してさまざまなイベントを設定できます。したがって、基本的には「EventTypeResource」もあるとよいでしょう。

次に、イベントが発生するたびに、イベントのタイプ(EventTypeResourceコレクションの要素を指定することによって)と次のような追加データを指定する「EventResource」にPOSTするだけです。

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.");
    }
);
于 2012-03-16T20:40:22.330 に答える