简体   繁体   中英

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": "test@example.co.uk",
    "first_name": "Admin",
    "last_name": "User"
},
{
    "id": 2,
    "email": "test1@example.co.uk",
    "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
        }
    ]
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM