Home > OS >  Name returning a number after serializing data
Name returning a number after serializing data

Time:11-05

I have a table service :

from django.db import models
from users.models import CustomUser

SERVICE_CHOICES = (
    ('Carpenter', 'Carpenter'),
    ('Driver', 'Driver'),
    ('Ambulanve', 'Ambulanve'),
    ('Spa', 'Spa'),
    ('Barber', 'Barber'),
    ('Cleaning', 'Cleaning'),
    ('Cook', 'Cook'),
)



class Service(models.Model):
    name  = models.ForeignKey(CustomUser, on_delete=models.CASCADE, limit_choices_to={'is_worker': True},)

    service = models.CharField(choices=SERVICE_CHOICES,max_length=100)

    def __str__(self):
        return f'{self.service} - {self.name}'

and a table CustomUser :

from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    is_worker = models.BooleanField(default=False)
    is_customer = models.BooleanField(default=True)

I am serializing the Service table below :

from rest_framework import serializers

from django.contrib.auth.models import User
from .models import *

class ServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields = '__all__'

But when I add a service from the admin panel, the name shows a number in the browser and not the string. How do I change it to show a the name and not a number? enter image description here

CodePudding user response:

This is because name is a forignkey to CustomUser, and the default behavior is to return the PK related to the CustomUser instance.

Instead you could use SerializerMethodField.

class UserSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()

    class Meta:
        model = Service
        fields = '__all__'

    def get_name(self, obj):
        return obj.name.first_name

CodePudding user response:

In your ServiceSerializer you can try:

class ServiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Service
        fields = '__all__'

    def to_representation(self, instance):
        rep = super(ServiceSerializer, self).to_representation(instance)
        rep['name'] = instance.name.name    # instance.name.what_you_use_in_Custom_User_model_to_represent_name
        return rep

However, consider whether this is what you want, because this change could lead to more problems than it solves.

  • Related