我刚刚开始使用 Tastypie 并试图弄清楚如何按照我的意愿格式化输出(我只对 GET 方法感兴趣)。我有一个可能有多个问题的测验对象,每个问题可能在多个测验中(因此是多对多,而不是一对多) - 但是当有人通过 API 请求测验对象时,我只想返回一个 ( json) 问题数组,我不想/不需要显示中间关系表数据。
一些代码:
模型.py:
class Question(models.Model):
owner = models.ForeignKey(User)
created_date = models.DateTimeField('date created',default=datetime.now)
lastupdated_date = models.DateTimeField('date updated',default=datetime.now)
title = models.CharField(max_length=500)
def __unicode__(self):
return self.title
class Quiz(models.Model):
owner = models.ForeignKey(User)
created_date = models.DateTimeField('date created',default=datetime.now)
lastupdated_date = models.DateTimeField('date updated',default=datetime.now)
title = models.CharField(max_length=200)
description = models.TextField(blank=True)
props = models.TextField(blank=True)
questions = models.ManyToManyField(Question, through='QuizQuestion')
def __unicode__(self):
return self.title
class QuizQuestion(models.Model):
quiz = models.ForeignKey(Quiz)
question = models.ForeignKey(Question)
order = models.IntegerField(default=1)
和资源.py:
class QuizResource(ModelResource):
q = fields.ToManyField('mquiz.api.resources.QuizQuestionResource', 'quizquestion_set', related_name='quiz', full=True)
class Meta:
queryset = Quiz.objects.all()
allowed_methods = ['get']
fields = ['title', 'id']
resource_name = 'quiz'
include_resource_uri = False
class QuizQuestionResource(ModelResource):
question = fields.ToOneField('mquiz.api.resources.QuestionResource', 'question', full=True)
class Meta:
queryset = QuizQuestion.objects.all()
allowed_methods = ['get']
include_resource_uri = False
class QuestionResource(ModelResource):
class Meta:
queryset = Question.objects.all()
allowed_methods = ['get']
fields = ['title']
resource_name = 'question'
include_resource_uri = False
这功能足够好,但不能完全给出我想要的输出。它给了我输出:
{
"id": "1",
"q": [
{
"id": "1",
"order": 1,
"question": {
"title": "What is the capital of Latvia?"
}
},
{
"id": "2",
"order": 2,
"question": {
"title": "What is the capital of Ethiopia?"
}
}
],
"title": "Capitals"
}
但是,我真正想要的是这种格式的输出,因为我不需要显示所有中间表 id/order 字段:
{
"id": "1",
"q": [
{
"title": "What is the capital of Latvia?"
},
{
"title": "What is the capital of Ethiopia?"
}
],
"title": "Capitals"
}
有没有办法做到这一点?非常感谢任何帮助/指针。
更新:使用这样的自定义序列化程序似乎有效:
class QuizJSONSerializer(Serializer):
json_indent = 2
def to_json(self, data, options=None):
options = options or {}
data = self.to_simple(data, options)
for question in data['q']:
del question['id']
del question['order']
for qkey, qvalue in question['question'].items():
question[qkey] = qvalue
del question['question']
return simplejson.dumps(data, cls=json.DjangoJSONEncoder,
sort_keys=True, ensure_ascii=False, indent=self.json_indent)
当然,可能有更通用的编码方式 - 但现在有效。