Serialize multiple models and send all in one json response django rest framework

Viewed 16314

This question is being asked to expand and fill in the holes from this one: Return results from multiple models with Django REST Framework

my goal is to return a json object that I will use to dynamically populate the options in various select statements in my html code.

so I want to grab a attribute from model a, another from model b etc

then I want all the values from attribute a and b and c etc

to be in a value as a JSON array to a key so

json = {
    modelA: {'atter1, atter2, atter3}
    modelB: {'atter1, atter2, atter3}
    model..:{you get the point}
}

this part from the post referenced above makes sense:

class TimelineViewSet(viewsets.ModelViewSet):
    """
    API endpoint that lists all tweet/article objects in rev-chrono.
    """
    queryset = itertools.chain(Tweet.objects.all(), Article.objects.all())
    serializer_class = TimelineSerializer

what doesn't is this:

class TimelineSerializer(serializers.Serializer):
    pk = serializers.Field()
    title = serializers.CharField()
    author = serializers.RelatedField()
    pub_date = serializers.DateTimeField()

how do I set the the seperate model attributes to the correct json key?

I assume its something similar to a serializer relation but these values aren't related to eachother via onetoone, onetomany, or many to many. I just want to grab all this info at once instead of creating an api for each value.

I am a lost little girl and I am asking you to help me find my way home.

2 Answers

I had a same situation to serialize multiple models to fetch filtered output from each serialize model to use from one single api. I came across this module to achieve this result.

Related