Hi, new Django user here hoping to get some pointers!
I’m trying to update sibling Stock objects as well as the parent Portfolio object when a user edits or creates a new Stock, but I haven’t been able to figure out how to make things work. So far, I’ve tried implementing this logic as part of the save override directly (as shown in the screenshot), as well as in the pre/post_save methods but I haven’t been able to figure it out.
class Portfolio(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
description = models.CharField(max_length=200,default=None)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
total_value = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
def get_stocks_children(self):
return self.stock_set.all()
class Stock(models.Model):
EQUITY_MASTER_LIST = utils.EQUITY_MASTER_LIST
portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE)
symbol = models.CharField(blank=False, max_length=10, choices=EQUITY_MASTER_LIST, default=None)
shares = models.DecimalField(blank=False, max_digits=12, decimal_places=4, default=1.0000)
portfolio_percentage = models.DecimalField(max_digits=10, decimal_places=4, default=0.0000)
purchase_date = models.DateField(null=True, blank=False, default=None)
purchase_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
sell_stop_price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
created = models.DateTimeField(auto_now_add=True)
modified = models.DateTimeField(auto_now=True)
def save(self, *args, **kwargs):
self.update_stocks_and_portfolio()
super().save(*args, **kwargs)
def update_stocks_and_portfolio(self):
#calc sell_stop_price; need to update for actual calc later
self.sell_stop_price = self.purchase_price / 4 * 3
#calc portfolio total value
portfolio = self.portfolio
stocks_in_portfolio = portfolio.get_stocks_children()
value = 0
for stock in stocks_in_portfolio:
value += stock.shares * stock.purchase_price
portfolio.total_value = value
#calc percentage weight of stock in portfolio total value
for stock in stocks_in_portfolio:
percentage = stock.shares * stock.purchase_price / value
stock.portfolio_percentage = percentage
The code does seem to work when I run it directly in the Django shell, but does not update the fields for portfolio_percentage (in the Stock model) or the total_value file (from the Portfolio model) when it runs as part of the save methods in the app itself.
Thanks in advance for any pointers on how to best accomplish this!