djangodjango-rest-frameworksumdjango-serializerrelation

Sum in Django Rest Framework (DRF) Serializer


Excuse me devs, i wanna ask about how to count on drf serializer, i need codes that can serialized fields plant from table A and it relations with another table B with count of them "plants_active"

Here's my code:

# Models
class TablePlants(models.Model):
    plant_id = models.CharField(primary_key=True, max_length=20, unique=True)
    gateway = models.ForeignKey(
        TableGatewayDevice, models.DO_NOTHING, blank=True, null=True)
    name = models.CharField(max_length=150, blank=True, null=True)
    date = models.DateField(blank=True, null=True)
    contact_person = models.CharField(max_length=70, blank=True, null=True)
    contact_email = models.CharField(max_length=50, blank=True, null=True)
    contact_phone = models.CharField(max_length=30, blank=True, null=True)
    plant_status = models.CharField(max_length=20, blank=True, null=True)
    weather_status_code = models.ForeignKey(
        TableAuxWeather, models.DO_NOTHING, db_column='weather_status_code', blank=True, null=True)
    timezone = models.CharField(max_length=200, blank=True, null=True)
    image = models.FileField(
        upload_to='plants/', validators=[file_size, validate_file_extension], null=True, blank=True)

    class Meta:
        db_table = 'table_plants'

    def __str__(self):
        return 'TablePlants[id: {id}, name: {name}]'.format(
            id=self.id, name=self.name)


class PVOwner(models.Model):
    pv_owner_id = models.AutoField(primary_key=True)
    company = models.ForeignKey(TableCompany, on_delete=CASCADE,
                                blank=True, null=True, related_name="pv_owner_company")

    class Meta:
        db_table = 'table_pv_owner'


class TableSitePlant(models.Model):
    pv_owner = models.ForeignKey(
        PVOwner, on_delete=CASCADE, blank=True, null=True, related_name="pv_site_owner_plant")
    site_owner = models.ForeignKey(
        SiteOwner, on_delete=CASCADE, blank=True, null=True, related_name="site_owner_plant")
    plant = models.ForeignKey(TablePlants, on_delete=CASCADE,
                              blank=True, null=True, related_name="site_plant")

    class Meta:
        db_table = 'table_site_plant'


# Serializer
class MainMenuSerializer(serializers.ModelSerializer):
    plants_active = serializers.IntegerField(source="plant")

    class Meta:
        model = TableSitePlant
        fields = ['plants_active']

# Views
@permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
    queryset = TableSitePlant.objects.all().filter(plant__plant_status='offline')
    serializer_class = OverviewPlantsActiveSerializer
    lookup_field = 'pv_owner'

What i expecting is i can count how many plants that have status online


Solution

  • You can use the get method to return response as you desired.

    @permission_classes([AllowAny])
    class OverviewPlantsActiveView(generics.RetrieveAPIView):
        queryset = TableSitePlant.objects.all().filter()
        serializer_class = OverviewPlantsActiveSerializer
        lookup_field = 'pv_owner'
    
        def get(self, request):
            queryset = self.get_queryset().filter(plant__plant_status='online')
            return Response({
                "active_plants": queryset.count(),
            })