Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DRF serialization - many-to-many field with through

How to serialize data from many-to-many field with through parameter? I have 3 models:

class Ingredient(models.Model):
    name = models.CharField(
        max_length=200,
    )
    measurement_unit = models.CharField(
        max_length=200,
    )

class Recipe(models.Model):
    name = models.CharField(
        max_length=200,
    )
    ingredients = models.ManyToManyField(
        Ingredient,
        through='RecipeIngredientsDetails',
    )

class RecipeIngredientsDetails(models.Model):
    recipe = models.ForeignKey(
        Recipe,
        on_delete=models.CASCADE,
    )
    ingredient = models.ForeignKey(
        Ingredient,
        on_delete=models.CASCADE,
    )
    amount = models.FloatField()

My serializers:

class IngredientSerializer(ModelSerializer):
    # amount = ???

    class Meta:
        model = Ingredient
        fields = ["id", "name", "amount", "measurement_unit"]
        
class RecipeSerializer(ModelSerializer):
    class Meta:
        model = Recipe
        fields = ["name", "ingredients"]
        depth = 1

Now, I get:

{
"name": "Nice title",
"ingredients": [
{
    "id": 1,
    "name": "salt",
    "measurement_unit": "g"
},
{
    "id": 2,
    "name": "sugar",
    "measurement_unit": "g"
}
]
}

I need amount-value in every ingredient. How can I implement it?

like image 917
Константин Avatar asked Dec 17 '25 14:12

Константин


1 Answers

You need to change IngredientSerializer to use the RecipeIngredientsDetails model, and also explicitly set the related serializer inside the RecipeSerializer:

from rest_framework.serializers import ReadOnlyField

class IngredientDetailSerializer(ModelSerializer):
    id = ReadOnlyField(source='ingredient.id')    
    ingredient = ReadOnlyField(source='ingredient.name')
    measurement_unit = ReadOnlyField(source='ingredient.measurement_unit')

    class Meta:
        model = RecipeIngredientsDetails
        fields = ["id", "ingredient", "measurement_unit", "amount",]
        
class RecipeSerializer(ModelSerializer):
    ingredients = IngredientDetailSerializer(source="recipeingredientsdetails_set", many=True)

    class Meta:
        model = Recipe
        fields = ["name", "ingredients"]
        depth = 1
like image 127
drec4s Avatar answered Dec 19 '25 05:12

drec4s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!