この質問が出されてから2年が経ちましたので、OPには明らかに遅れています。しかし、私のように同様のジレンマを抱えていた他の人のために、これを成し遂げるためのピストニックな方法が存在します.
投票と選択肢の Django の例を使用する -
ChoiceHandler の場合、JSON 応答は次のようになります。
[
{
"votes": 0,
"poll": {
"pub_date": "2011-04-23",
"question": "Do you like Icecream?",
"polling_ended": false
},
"choice": "A lot!"
}
]
これには、関連するポーリングの JSON 全体が含まれますが、idそれよりも優れているとは言えません。
望ましい応答は次のとおりです。
[
{
"id": 2,
"votes": 0,
"poll": 5,
"choice": "A lot!"
}
]
これを達成するためにハンドラーを編集する方法は次のとおりです。
from piston.handler import BaseHandler
from polls.models import Poll, Choice
class ChoiceHandler( BaseHandler ):
allowed_methods = ('GET',)
model = Choice
# edit the values in fields to change what is in the response JSON
fields = ('id', 'votes', 'poll', 'choice') # Add id to response fields
# if you do not add 'id' here, the desired response will not contain it
# even if you have defined the classmethod 'id' below
# customize the response JSON for the poll field to be the id
# instead of the complete JSON for the poll object
@classmethod
def poll(cls, model):
if model.poll:
return model.poll.id
else:
return None
# define what id is in the response
# this is just for descriptive purposes,
# Piston has built-in id support which is used when you add it to 'fields'
@classmethod
def id(cls, model):
return model.id
def read( self, request, id=None ):
if id:
try:
return Choice.objects.get(id=id)
except Choice.DoesNotExist, e:
return {}
else:
return Choice.objects.all()