Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - Get full related objects in list

I'm rather new to Django Rest Framework and I'm trying to use DRF to to serialize a list of (related) objects.

I have the following models:

class Answer(models.Model):
   value = models.CharField(max_length=128)

class User(models.Model):
   name = models.CharField(max_length=128)
   age = models.PositiveIntegerField()

class UserAnswer(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)

And the result I'm trying to get is in this form:

[
    {
     "name": "myName1",
     "answers": [
        {
          "value": "myFirstAnswer"
        },
        {
          "value": "mySecondAnswer"
        },
        {
          "value": "myThirdAnswer"
        },
        ]
    },
    {
     "name": "myName2",
     "answers": [
        {
          "value": "myFirstAnswer"
        },
        {
          "value": "mySecondAnswer"
        },
        {
          "value": "myThirdAnswer"
        },
        ]
    }
]

I'm trying to do it this way now:

class UserAnswerSerializer(serializers.ModelSerializer):
    answers = AllUserAnswersSerializer(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('name', 'answers')

But then I get the following result:

[
    {
        "name": "myName1"
    }, 
    {
        "name": "myName2"
    }
]

And when I try to do it this way:

class UserAnswerSerializer(serializers.ModelSerializer):
    answers = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    class Meta:
        model = User
        fields = ('name', 'answers')

Then i get the following result (an example again):

[
    {
     "name": "myName1",
     "answers": [
        1,
        2,
        3
        ]
    },
    {
     "name": "myName2",
     "answers": [
        4,
        5,
        6
        ]
    }
]

I'm having a hard time making this work, hope someone can show me how to convert the Primary Key's to actual objects!

Thanks!

like image 402
ZvL Avatar asked Feb 25 '15 14:02

ZvL


1 Answers

Remove the explicit definition of the answers field in your serializer and add depth=1. It should look like this:

class UserAnswerSerializer(serializers.ModelSerializer):
    class Meta:
        depth = 1
        model = User
        fields = ('name', 'answers')

Info about depth: http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

like image 78
argaen Avatar answered Oct 30 '22 04:10

argaen