[Answered ]-Accss ManyToMany through model attribute for spcific row in drf serilizaer

1👍

Here is a solution I’ve found, not sure about query efficiency though.
I’m passing down the chart_id in the serialzier context using to_representation on the chart serializer.

My serializers:

class MonitoredFlowSerializerForChart(serializers.ModelSerializer):
    is_visible = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = MonitoredFlow
        fields = ['id', 'is_visible', 'name']        

    def get_is_visible(self, obj):
        result = obj.chartflow_set.get(chart_id=self.context.get("chart_id"))
        return result.is_monitored_flow_visible_on_chart

class ChartSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    monitored_flows = MonitoredFlowSerializerForChart(many=True, required=False,
                                                      max_length=MAX_AMOUNT_OF_MONITORED_FLOWS_PER_CHART)

    class Meta:
        model = Chart
        fields = ['id', 'user', 'name', 'monitored_flows']

    def to_representation(self, instance):
        self._context["chart_id"] = instance.id
        return super().to_representation(instance)

Leave a comment