[Django]-Django Rest Framework group objects dynamically

2👍

First note, according to your example you are grouping by product, so you are not looking for a MixView but for ProductView.

What you could do:

# Serializers
class MixSerializer(serializer.ModelSerializer):
    ingredient_name = serializers.CharField(source='ingredient.name')
    class Meta:
        model = Mix
        fields = ('ingredient_name', 'percentage')

class ProductSerializer(serializer.ModelSerializer):
    ingridients = MixSerializer(many=True, read_only=True)
    class Meta:
        model = Product
        fields = ('name', 'ingridients')

# Views
class ProductView(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer

Should give you something like:

{
    "name": "White Russian",
    "ingredients": [
        {"ingredient_name": "Vodka", "percentage" : 0.54},
        {"ingredient_name": "Coffee Liquer", "percentage" : 0.27},
        {"ingredient_name": "Single Cream", "percentage" : 0.19}
    ]
}

P.S. To make it non read only you will need to also implement create and update methods under ProductSerializer

Leave a comment