Ad

Use Of Property Decorator In Django To Calculate Sum

I have two moldes in which one model consists of file field. I have to calculate total size of the files in the parent model within the property decorator. I think this could also be done inside the serializer class using the serializer method but I want within the property decorator.

class Package(models.Model):   

    name = models.CharField(max_length=50,blank=True)
    />....................other fields.........../

    **/.........problem is here..../**
    @property
    def folder_size(self):
        all = self.details.all()
        
        all.annotate()
        return total

Here I need help to calculate the sum of all files sizes of a single package.

Class Details(models.Model):
    package = models.ForeignKey(Package, on_delete=models.CASCADE,null=True,
                               related_name='details')
    notes = models.FileField(blank=True, null=True)

    @property
    def file_size(self):
        return self.file.size
Ad

Answer

You can not use properties in a .annotate(…) clause [Django-doc] or any other queryset expression: these are done at the database side and the database does not know anything about properties, models, or Python.

Furthermore we can not transform this expression into something the queryset can understand, since a FileField only stores the path of the file, not its size.

You thus will need to manually determine the size, for example with:

class Package(models.Model):
    # …
    
    @property
    def folder_size(self):
        return sum(detail.file_size for detail in self.details.only('file'))

here the .only(…) clause [Django-doc] can limit the bandwidth by only fetching the file column, but still the processing has to be done at the Python/Django level.

Ad
source: stackoverflow.com
Ad