Home > Blockchain >  Django Model Calculated field as Database level?
Django Model Calculated field as Database level?

Time:01-13

I have the simplified model below :

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.FloatField()

class Invoice(models.Model):
    product = models.ForeignKey(Product,on_delete=models.PROTECT)
    quantity = models.FloatField()

    @property
    def total(self):
        return self.quantity * self.product.price

I would like to be able to process data analysis on my Invoices data. If i load my queryset to a list, the total property is missing :

Invoice.object.all().values_list()

Is there a way with django to calculate the property field as a database level ? So it would be easy to analyse from queryset (ideally i would like to load in dataframe)

Thanks for the tips !

CodePudding user response:

a lazy method to do until you find better way

result = [{
    "id": invoice.id,
    "product": invoice.product,
    "quantity": invoice.quantity,
    "total": invoice.total,
} for invoice in Invoice.object.all()]

CodePudding user response:

Based on B. Okba answer, I've slightly adapted in my code, converting first to a dataframe, and then calling for the total value :

from django_pandas.io import read_frame
df = read_frame(Invoice.objects.all())
df['total'] = df.apply(lambda x: Invoice.objects.get(id=x['id']).total,axis=1)

But i'm still curious if there is a nicer way/more efficient way to handle.

  •  Tags:  
  • Related