Mnvxmanu
Mnvxmanu

Reputation: 21

Serializer is returning "Model object" instead of specific field

I have a problem. I'm creating an API with Django REST framework and I created serializer to return recipes and ingredients to cook it.

models.py:

class Recipes(models.Model):
        title = models.CharField(max_length=50,null=True, blank=False, verbose_name=('name'))

class Tag(models.Model):
        name = models.CharField(max_length=50,null=True, blank=False, verbose_name=('name'))

class ListTag(models.Model):
        recipes = models.ForeignKey(Recipes, blank=False, on_delete=models.CASCADE, related_name='recipes')
        tag = models.ForeignKey(Tag, blank=False, on_delete=models.CASCADE, related_name='tag')

I have the classes Recipes, Tag (ingredients) and ListTag is the list that contains each ingredient with the id of the receipt.

serializers.py

class RecipesSerializer(serializers.ModelSerializer):
    ingredient = serializers.StringRelatedField(many=True, read_only=True, source='recipes')
    class Meta:
        model = Recipes
        fields = ('title', 'ingredient')

class TagSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag

class ListTagSerializer(serializers.ModelSerializer):
    tag = serializers.SlugRelatedField(
        read_only=True,
        slug_field='name'
     )
    class Meta:
        model = ListeTag
        fields = ('recipes','tag')

Results

For RecipesSerializer

{
    "title": "Pancakes à la canadienne",
    "ingredient": [
        "ListTag object",
        "ListTag object",
        "ListTag object"
    ]
}

But I want

{
    "title": "Pancakes à la canadienne",
    "ingredient": [
         {
             "id": 2,
             "name": "milk"
         },
         {
             "id": 3,
             "name": "rice"
         },
         {
             "id": 4,
             "name": "salade"
         },
         {
             "id": 5,
             "name": "tomato"
         }
    ]
}

or

{
    "title": "Pancakes à la canadienne",
    "ingredient": ["milk","rice","salade","tomato"]
}

Upvotes: 2

Views: 609

Answers (1)

Anush Devendra
Anush Devendra

Reputation: 5475

You can do this by using Nested relationships like:

class RecipesSerializer(serializers.ModelSerializer):
    recipes = ListTagSerializer(many=True,read_only=True)
    class Meta:
        model = Recipes
        fields = ('title', 'recipes')

class ListTagSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField(source='tag.id')
    tag = serializers.SlugRelatedField(
        read_only=True,
        slug_field='name'
    )
    class Meta:
        model = ListeTag
        fields = ('id','tag')

Learn more about Nested relationships here

Upvotes: 1

Related Questions