Home > Net >  How to get product count from parent in django rest framework
How to get product count from parent in django rest framework

Time:10-05

a'm new in django, I have one model like this

class Category(models.Model):
    title = models.CharField(max_length=200)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

Parent - foods subparent - Italian food, French food and other pizaa, Polenta, Lasagna

Parent - drinks subparent - juice, alkohol water, tea, leamon tea

Can i count in serializer foods count - 3 drinks count - 4

CodePudding user response:

You mean something like this ?

class Category(serializers.ModelSerializer):
    no_of_children = serializer.IntegerField(read_only=True)

    class Meta:
        model = Category
        fields = ('title', 'no_of_children',)
    
    @staticmethod
    def prefetch_related(queryset):
        return queryset.annotate(
            no_of_children=Count('children')
        )

Remember to call prefetch_related method in your view eg.

queryset = serializer.prefetch_related(Category.objects.all())

CodePudding user response:

use the @property method. https://djangocentral.com/property-decorator-explained/ it may help.

  • Related