Django serializing json

I'm building an API using django and I have come across a problem.
I have a UserDetail model that has a foreing key to a User model.

class UserDetail(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    about = models.CharField(max_length=200, default="", blank=True)

I want to serialize the information of User and the information of UserDetails in one json and this is what I'm currently doing:

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email')


class DetailSerializer(serializers.ModelSerializer):

    user = UserSerializer(required=True)

    class Meta:
        model = UserDetail
        fields = ('user', 'about',)

Right now I obtain this:

{
    "user": {
        "username": "julia",
        "first_name": "antonia",
        "last_name": "uri",
        "email": "as¡¡[email protected]"
    },
    "about": ""
}

But I want to obtain the information of UserDetail from User, not the other way around (like I'm currently doing) so that I get the information like this:

{
    "username": "julia",
        "first_name": "antonia",
        "last_name": "uri",
        "email": "[email protected]",
    "details": {
        "about": ""
    }
}

I would really appreciate if someone could tell me what I'm doing wrong.

Thank you!

Edit
Here is my view:

#user = User.objects.select_related('userdetail').get(username=username)
        user = User.objects.get(username=username)
        userDetail = UserDetail.objects.get(user=user)

        if request.method == 'GET':
            serializer = DetailSerializer(userDetail)
            return Response(serializer.data)

Upvotes: 1

Views: 53

Answers (1)

zelenyjan
zelenyjan

Reputation: 703

You can do it this way:

class DetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserDetail
        fields = ('about',)

class UserSerializer(serializers.ModelSerializer):
    details = DetailSerializer(many=False, source="userdetail")

    class Meta:
        model = User
        fields = ('username', 'first_name', 'last_name', 'email', 'details')

source=userdetail is how you access userdetail from User model instance

Upvotes: 1

Related Questions