1

I have next ModelSerializers.

I need the statistics data display at 6 days range by default (see date field in StatisticSerializer). User can to change this date range (from frontend get two parameters: start_date and end_date, which not is in Models and Serializers. How can I make this functional?

serializers

class StatisticSerializer(serializers.ModelSerializer):
    class Meta:
        model = Statistic
        fields = ['date', 'clicks', 'page_views']


class UserStatisticSerializer(serializers.ModelSerializer):
    statistics = StatisticSerializer(many=True)

    class Meta:
        model = User
        fields = [
            'first_name', 'last_name', 'gender', 'ip_address', 'statistics',
        ]

views

class UserStatisticApiView(RetrieveAPIView):
    serializer_class = UserStatisticSerializer
    queryset = User.objects.all()
1
  • Are users supposed to see all users' statistics or just their own? Commented Jan 17, 2020 at 8:14

1 Answer 1

3

you can use SerializerMethodField(), docs enter link description here

there just some Pseudocode

class StatisticSerializer(serializers.ModelSerializer):
    class Meta:
        model = Statistic
        fields = ['date', 'clicks', 'page_views']


class UserStatisticSerializer(serializers.ModelSerializer):
    filtered_statistc = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = [
            'first_name', 'last_name', 'gender', 'ip_address', 'filtered_statistc',
        ]

    def get_filtered_statistc(self,obj):
        result = Statistic.objects.filter('filter there by your params')
        serialized_result = StatisticSerializer(data=result, many=True)
        return serialized_result
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.