Home > OS >  Django rest_framework : count objects and return value to serializer
Django rest_framework : count objects and return value to serializer

Time:11-13

i need to count all supporters in model and return value to serializer

models.py

class Supporters(models.Model):
    name = models.CharField(max_length=255)
    img = models.ImageField(upload_to="Supporters", blank=True, null=True)

serializers.py

class SupportersSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()
    supporters_count = serializers.SerializerMethodField()

    class Meta:
        model = Supporters
        fields = ("id", "name", "img", "supporters_count")

        def get_supporters_count(self, obj):
            return obj.supporters_count.count()

views.py

class SupportersViwe(generics.RetrieveAPIView): queryset = Supporters.objects.all()
    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = SupportersSerializer(queryset, many=True)
        return Response(serializer.data)

CodePudding user response:

About your serializer file, beware of indentation, here is an example. As for counting objects, i believe you are looking for something like this:

class SupportersSerializer(serializers.ModelSerializer):
    id = serializers.ReadOnlyField()
    supporters_count = serializers.SerializerMethodField()

    class Meta:
        model = Supporters
        fields = ("id", "name", "img", "supporters_count")

    def get_supporters_count(self, obj):
        return Supporters.objects.count()

As specified in the queryset documentation. It is also possible to use the asynchronous version since Django version 4.1:

Asynchronous version: acount()
  • Related