Santhosh
Santhosh

Reputation: 11844

django rest framework: customize nested serializer

I have the following Django model structure:

class TypeOfIngredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)

class Ingredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)
    typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT)

Serializer:

class IngredientListSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = '__all__'

With the above serializer i see the following api output:

"results": [
        {
            "id": 1,
            "name": "adrak",
            "slug": "adrak",
            "typeofingredient": null
        },
        {
            "id": 2,
            "name": "banana",
            "slug": "banana",
            "typeofingredient": 1
        },

How to get "typeofingredient": "fruit" where fruit is the name field of the typeofingredient. What i am getting is the id.

I tried nested:

class IngredientListSerializer(ModelSerializer):
    class Meta:
        model = Ingredient
        fields = '__all__'
        depth = 1

Then i get the api output as:

"results": [
        {
            "id": 1,
            "name": "adrak",
            "slug": "adrak",
            "typeofingredient": null
        },
        {
            "id": 2,
            "name": "banana",
            "slug": "banana",
            "typeofingredient": {
                    "id": 1,
                    "name": "fruit",
                    "slug": "fruit"
            }
        },

Here is showing all the details of the typeofingredient. Rather than this can i have directly "typeofingredient": "fruit"

Upvotes: 0

Views: 1327

Answers (2)

Shaon shaonty
Shaon shaonty

Reputation: 1425

You can add str method on models.py

class TypeOfIngredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)

    def __str__(self):
        return str(self.name)

class Ingredient(models.Model):
    name = models.CharField(max_length=200,unique=True,null=False)
    slug = models.SlugField(unique=True)
    typeofingredient = models.ForeignKey(TypeOfIngredient, related_name='typeof_ingredient',null=True, blank=True,on_delete=models.PROTECT)

Upvotes: 1

Satendra
Satendra

Reputation: 6865

Use serializers.ReadOnlyField

class IngredientListSerializer(ModelSerializer):
    typeofingredient = serializers.ReadOnlyField(source='typeofingredient.name')    

    class Meta:
        model = Ingredient
        fields = '__all__'

Upvotes: 1

Related Questions