Reputation: 35
I'm new in django trying to do a project of management of a small restaurant, in my consummation model,I have attributes that are foreign keys, and the date of consummation, now I try to calculate the sum of those attributes in a method inside the model by returning the total.
I tried
class Consommation(models.Model):
entree = models.ForeignKey(Entree, models.CASCADE, verbose_name="L'entree", null=True, blank=True)
food = models.ForeignKey(Meals, models.CASCADE, verbose_name='Plat de resistance', null=True, blank=True)
dessert = models.ForeignKey(Dessert, models.CASCADE, verbose_name='Dessert', null=True, blank=True)
boisson = models.ForeignKey(Boisson, models.CASCADE, verbose_name='Boisson', null=True, blank=True)
autres = models.ForeignKey(Autres, models.CASCADE, verbose_name='Snacks', null=True, blank=True)
consomme_le = models.DateTimeField(default=timezone.now, editable=False)
class Facture(models.Model):
consommation = models.OneToOneField(Consommation, models.CASCADE, null=True, blank=True,
verbose_name='Facture')
fait_le = models.DateField(default=timezone.now, editable=False)
is_regle = models.BooleanField(default=False, verbose_name='Est regle')
initials_caissier = models.CharField(max_length=5, verbose_name='Initiales du Caissier')
def __str__(self):
return 'Facture du :' + ' ' + str(self.fait_le)
def get_absolute_url(self):
return reverse('clients:facture_detail', kwargs={'pk': self.pk})
def net_a_payer(self):
if self.consommation:
if not self.consommation.entree:
self.consommation.entree.price = int(0)
if not self.consommation.food:
self.consommation.food.price = int(0)
if not self.consommation.dessert:
self.consommation.dessert.price = int(0)
if not self.consommation.boisson:
self.consommation.boisson.price = int(0)
if not self.consommation.autres:
self.consommation.autres.price = int(0)
return self.consommation.entree.price + self.consommation.food.price + self.consommation.dessert.price + self.consommation.boisson.price + self.consommation.autres.price
I expect the result to be the sum of the attibutes instead of returning "None"
Upvotes: 2
Views: 38
Reputation: 476557
If a function does not explicitly return something, it will return None
. So your function will here only return a value in case all the conditions in this cascade of conditions hold.
That being said, you make things too complex, you can simply define a helper function, and sum up the prices:
class Facture(models.Model):
# ...
@staticmethod
def get_price(item, _default=0):
if item:
return item.price
return _default
def net_a_payer(self):
get_price = Facture.get_price
con = self.consummation
return get_price(con.entree) + get_price(con.food) + get_price(con.dessert) + get_price(con.boisson) + get_price(con.autres)
You might however want to consider remodeling this. For example making a general model "expense", and adding a category to it. That way, you can easily sum on the database level.
Upvotes: 2