9๐
โ
Is there a way I can get around this so that I can do the receipt query in the
Employee
property?
Yes, you can import the module in the method:
from django.db import models
class Employee(models.Model):
number = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
@property
def receipt_sum(self):
from receipts.models import Receipt
receipts = Receipt.objects.filter(Employee=self.pk)
sum = 0
for receipt in receipts:
sum += receipt.amount
return sum
but it is actually not necessary to import Receipt
at all, you can make use of the receipt_employee
relation to access the related Receipt
object, and you can use .aggregate(โฆ)
[Django-doc] to sum up the elements at the database side, this is likely more efficient:
from django.db import models
from django.db.models import Sum
class Employee(models.Model):
number = models.CharField(max_length=50, unique=True)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
@property
def receipt_sum(self):
return self.receipt_employee.aggregate(
total=Sum('amount')
)['total'] or 0
Source:stackexchange.com