Serializing ManyToMany relationship with intermediary model in Django Rest Framework

Viewed 5222

I'm having some trouble serializing many to many relationships with a through argument in DRF3

Very basically I have recipes and ingredients, combined through an intermediate model that specifies the amount and unit used of a particular ingredient.

These are my models:

from django.db import models
from dry_rest_permissions.generics import authenticated_users, allow_staff_or_superuser
from core.models import Tag, NutritionalValue
from usersettings.models import Profile

class IngredientTag(models.Model):
    label = models.CharField(max_length=255)

    def __str__(self):
        return self.label


class Ingredient(models.Model):
    recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE)
    ingredient_tag = models.ForeignKey(IngredientTag, on_delete=models.CASCADE)
    amount = models.FloatField()
    unit = models.CharField(max_length=255)


class RecipeNutrition(models.Model):
    nutritional_value = models.ForeignKey(NutritionalValue, on_delete=models.CASCADE)
    recipe = models.ForeignKey('Recipe', on_delete=models.CASCADE)
    amount = models.FloatField()


class Recipe(models.Model):
    name = models.CharField(max_length=255)
    ingredients = models.ManyToManyField(IngredientTag, through=Ingredient)
    tags = models.ManyToManyField(Tag, blank=True)
    nutritions = models.ManyToManyField(NutritionalValue, through=RecipeNutrition)
    owner = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)

    def __str__(self):
        return self.name

And these are currently my serializers:

from recipes.models import Recipe, IngredientTag, Ingredient
from rest_framework import serializers

class IngredientTagSerializer(serializers.ModelSerializer):
    class Meta:
        model = IngredientTag
        fields = ('id', 'label')

class IngredientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ingredient
        fields = ('amount', 'unit')

class RecipeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Recipe
        fields = ('id', 'url', 'name', 'ingredients', 'tags', 'nutritions', 'owner')
        read_only_fields = ('owner',)
        depth = 1

I've searched SO and the web quite a bit, but I can't figure it out. It would be great if someone could point me in the right direction.

I can get the list of ingredients to be returned like so:

{
    "count": 1,
    "next": null,
    "previous": null,
    "results": [
        {
            "id": 1,
            "url": "http://localhost:8000/recipes/1/",
            "name": "Hallo recept",
            "ingredients": [
                {
                    "id": 1,
                    "label": "Koek"
                }
            ],
            "tags": [],
            "nutritions": [],
            "owner": null
        }
    ]
}

But what I want is for the amount and unit to also be returned!

3 Answers
Related