我刚刚开始使用Tastypie并且正在尝试按照我的意愿设计如何格式化输出(我只对GET方法感兴趣)。 我有一个测验对象可能有多个问题,每个问题可能在多个测验中(因此多对多,而不是一对多) - 但是当有人通过API请求测验对象时,我只想返回一个( json)数组的问题,我不希望/需要显示中间关系表数据。
一些代码:
Models.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)
和resources.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)
当然可能有更通用的方法对此进行编码 - 但现在可以使用。
答案 0 :(得分:3)
使用您自己的代码覆盖资源对象的序列化函数将是一个很好的方法,但是在脱水方法中重构数据包将是一个快速解决方法