[Answered ]-Django calculated fields on custom queryset

1👍

You can use SerializerMethodField

here is the docs
https://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

and I recommend to use ModelSerializer instead of Serializer.
Also I recommend keep serializer out of the view

class OutputSerializer(serializers.ModelSerializer):
    ...
    total_cost = serializers.SerializerMethodField("total_cost")

    def total_cost(self, obj: Recipe) -> int:
        """calculates the entire cost of producing the recipe"""
        total_recipe_cost = 0
        for r_ingredient in obj.get_recipe_ingredients():
            ingredient_cost = r_ingredient._get_individual_ingredient_cost()
            total_recipe_cost += ingredient_cost

        return total_recipe_cost


Leave a comment