bryan
bryan

Reputation: 1051

Django Rest Framework - Append JSON to Model Serialization

I have a model is pretty straight forward and I've created a property on the model to essentially return child data as JSON. The property is simple:

@property
def question_data(self):
    from api.models import TemplateQuestion
    questions = TemplateQuestion.objects.filter(template__id=self.template.id)
    question_dict = [obj.as_dict() for obj in questions]
    return(json.dumps(question_dict, separators=(',', ': ')))

Which does its job and outputs valid JSON. That said I'm at a total loss of how to add that property to the Serializer as JSON and not a string like

{
    "questions": "[{\"sequence\": 2,\"next_question\": \"\",\"modified_at\": \"2016-01-27T19:59:07.531872+00:00\",\"id\": \"7b64784e-a41d-4019-ba6e-ed8b31f99480\",\"validators\": []},{\"sequence\": 1,\"next_question\": null,\"modified_at\": \"2016-01-27T19:58:56.587856+00:00\",\"id\": \"99841d91-c459-45ff-9f92-4f75c904fe1e\",\"validators\": []}]"
}

It's stringifying the JSON and which I need as proper JSON.

Serializer is probably too basic but I haven't worked with DRF in a while and have never tried to append JSON to the serialized output.

class BaseSerializer(serializers.ModelSerializer):

    class Meta:
        abstract = True

class SurveySerializer(BaseSerializer):
        included_serializers = {
            'landing_page': 'api.serializers.LandingPageSerializer',
            'trigger': 'api.serializers.TriggerSerializer',
            'template': 'api.serializers.TemplateSerializer'
        }

        questions = serializers.ReadOnlyField(source='question_data')

        class Meta:
            model = Survey
            fields = ('id',
                      'name',
                      'slug',
                      'template',
                      'landing_page',
                      'trigger',
                      'trigger_active',
                      'start_date',
                      'end_date',
                      'description',
                      'fatigue_limit',
                      'url',
                      'questions',)
            meta_fields = ('created_at', 'modified_at')

I'll add that I'm also bolting on the Django Rest Framework JSON API formatting but I think that in the end I'm just not getting how to append JSON to a model's serialization without it being returned as a string.

Upvotes: 0

Views: 1581

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

You should not be dumping the results of the method to JSON. Just return the dict; DRF's serializer will take care of converting it.

Upvotes: 2

Related Questions