Serializing custom count field in DRF

Issue

I am trying to send a serialized custom field that has that count of all items in a category in a vessel;
I am trying to understand why this line works:

vessel_inventory_category_count = serializers.IntegerField(
        source='vessel_inventory_category.count',
        read_only=True
    )

but this doesnt :

 vessel_inventory_item_count = serializers.IntegerField(
        source='category_items.count',
        read_only=True
    )

serializer.py :

class VesselInfoSerializer(serializers.ModelSerializer):
    vessel_component_count = serializers.IntegerField(
        source='vessel_components.count',
        read_only=True
    )
    vessel_inventory_category_count = serializers.IntegerField(
        source='vessel_inventory_category.count',
        read_only=True
    )
    vessel_inventory_item_count = serializers.IntegerField(
        source='category_items.count',
        read_only=True
    )

class Meta:
    model = Vessel
    fields = '__all__' 

models.py

class Category(models.Model):
    name = models.CharField(max_length=150, null=True, blank=True)
    vessel = models.ForeignKey(
        Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_inventory_category')

    def __str__(self):
        return self.name


class Item(models.Model):
    name = models.CharField(max_length=150, null=True, blank=True)
    category = models.ForeignKey(
        Category, blank=True, null=True, on_delete=models.CASCADE, related_name='category_items')

    def __str__(self):
        return self.name

vessel model.py:

class Vessel(models.Model):
    name = models.CharField(max_length=255)
    imo = models.CharField(max_length=255)
    image = models.ImageField(blank=True, upload_to='vessel_image')

    def __str__(self):
        return self.name

Solution

vessel_inventory_item_count = serializers.SerializerMethodField()

def get_vessel_inventory_item_count(self, obj):
    # get vessel related category ids
    categories_id = list(obj.vessel_inventory_category.values_list('id', flat=True))
    # return count of those items which are related to vessel category
    return Item.objects.filter(category_id__in=categories_id).count()

Answered By – Shishir Subedi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published