samroberts707
samroberts707

Reputation: 171

Django Rest Framework User Model Serializer Nested

I am having some issues with my DRF Serializers. I essentially have a model that has Django users as Foreign keys so I can see who is attached to a job.

When I try and resolve these user ID's nested inside my Job serializer using a User serializer I only see the ID, but when I use the User serializer on it's own not nested I get the correct fields returned. Below is my code snippets. Any help would be great.

models.py

from profiles.models import UserProfile
class Job(models.Model):

    name = models.CharField(max_length=256, blank=False)
    designer_one = models.ForeignKey(UserProfile, related_name='designer_one', on_delete=models.DO_NOTHING)
    designer_two = models.ForeignKey(UserProfile, related_name='designer_two', on_delete=models.DO_NOTHING)

    def __str__(self):
        return self.name

    class Meta(object):
        verbose_name = "Job"
        verbose_name_plural = "Jobs"
        ordering = ['name']

serializers.py

from django.contrib.auth.models import User
class UsersSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'email', 'first_name', 'last_name')

class JobsSerializer(serializers.ModelSerializer):
    tasks = TasksSerializer(many=True, read_only=True)
    designer_one = UsersSerializer(many=False, read_only=True)
    designer_two = UsersSerializer(many=False, read_only=True)

    class Meta:
        model = Job
        fields = ('id', 'name', 'designer_one', 'designer_two', 'tasks')

What I get returned from UsersSerializer API View

[
{
    "id": 1,
    "email": "[email protected]",
    "first_name": "Admin",
    "last_name": "User"
},
{
    "id": 2,
    "email": "[email protected]",
    "first_name": "",
    "last_name": ""
}
]

What I get returned from JobsSerializer API View

{
    "id": 1,
    "name": "Test job",
    "designer_one": {
        "id": 1
    },
    "designer_two": {
        "id": 1
    },
    "tasks": [
        {
            "id": 1,
            "name": "Test Task",
            "job": 1
        }
    ]
}

Upvotes: 0

Views: 1188

Answers (1)

Ken4scholars
Ken4scholars

Reputation: 6296

The issue is that you are using UsersSerializer for model User, meanwhile designer_one and designer_two are of type UserProfiile.

You can allow DRF generate the nested serializers for you using the depth option as @Anup Yadav suggested but if you want to have control over which fields are displayed, you need to create your own serializer for Userprofile and use it in the Job serializer

Upvotes: 0

Related Questions