'How can to get data from related model in Django Rest Framework?

I have next models

class User(AbstractUser):
    ip_address = models.CharField(max_length=15)

class Statistic(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='statistics')
    clicks = models.PositiveSmallIntegerField()

and serializers

class UserListSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'first_name', 'ip_address']


class UserStatisticSerializer(serializers.ModelSerializer):
    class Meta:
        model = Statistic

How can I get in Response data in following format:

{
  'user_data': {
      'id': 1, 'first_name': 'name', ...,
      'statistics': [
          {'id': 1, 'clicks': 100},
          {'id': 3, 'clicks': 550}
      ]
}

I go to the link /api/v1/users/<int:pk>/ and call next function:

class UserDetailStatisticApiView(RetrieveAPIView):
    queryset = ???
    serializer_class = ???

Thnx for help



Solution 1:[1]

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 UserDetailStatisticApiView(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserStatisticSerializer

Solution 2:[2]

View

class UserDetailStatisticApiView(RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserListSerializer

                                                                            

Serializers

class UserStatisticSerializer(serializers.ModelSerializer):
    class Meta:
        model = Statistic
        fields = '__all__'


class UserListSerializer(serializers.ModelSerializer):
    statistics = SerializerMethodField()
    class Meta:
        model = User
        fields = ['id', 'first_name', 'statistics']
    
    def get_statistics(self,obj):
        statistics = Statistic.objects.filter(user=obj)
        return  UserStatisticSerializer(statistics, many=True).data 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 unknown
Solution 2