在 DRF 中序列化自定义计数字段

Serializing custom count field in DRF

我正在尝试发送一个序列化的自定义字段,其中包含容器中某个类别中所有项目的计数; 我试图理解为什么这条线有效:

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
    )

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

船只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
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()