4
我剛開始使用Tastypie,並試圖解決如何格式化輸出,因爲我想(我只對GET方法感興趣)。 我有一個可能有多個問題的測驗對象,每個問題可能在多個測驗(因此是多對多,而不是一對多) - 但是當有人通過API請求測驗對象時,我只想返回一個(json)數組的問題,我不想/不需要顯示中間關係表數據。Django tastypie多對多的關係 - 在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 /訂單字段顯示:
{
"id": "1",
"q": [
{
"title": "What is the capital of Latvia?"
},
{
"title": "What is the capital of Ethiopia?"
}
],
"title": "Capitals"
}
有沒有辦法做到這一點?任何幫助/指針非常感謝。
UPDATE: 使用像這樣的自定義串行器似乎工作:
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)
當然有可能實現代碼更通用的方法 - 但工程現在。
謝謝你 - 是一個自定義序列似乎要走的路。我用自定義序列化程序更新了我的問題 –