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
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.
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module