Question

I have the following django models:

class Equity(models.Model):
    symbol = models.CharField(max_length=128)
    dividend = models.DecimalField(max_digits=9, decimal_places=2)

class Portfolio(models.Model):
    name = models.CharField(max_length=128)
    holdings = models.ManyToManyField(Equity, through='PortfolioHolding')

class PortfolioHolding(models.Model):
    equity = models.ForeignKey(Equity)
    portfolio = models.ForeignKey(Portfolio)
    weight = models.FloatField(default=0.0)

I am attempting to make a formset that allows me to modify the dividend values of all holdings in a portfolio. Currently I have:

PortfolioHoldingDivFormSetBase = modelformset_factory(PortfolioHolding, extra=0, fields=['dividend',])

class PortfolioHoldingDividendFormset(PortfolioHoldingDivFormSetBase):
    def add_fields(self, form, index):
        super(SubPortfolioHoldingDividendFormset, self).add_fields(form, index)
        form.fields['is_checked'] = forms.BooleanField(required=False)

And in my view, I call the formset as follows:

formset = PortfolioHoldingDividendFormset(request.POST or None, queryset=p.portfolioholding_set.all().order_by('equity__symbol'))

where p is a valid Portfolio model object.

The problem is that the PortfolioHolding model does not contain the dividend field, rather the Equity model that is linked to the PortfolioHolding. I have tried changing the fields in the modelformset_factory to 'equity.dividend' which did not work. Is there

  1. Any way to access the other side of the through relationship in my formset? or
  2. Is it possible to come from the other direction- creating my modelformset_factory for the Equity model, then in my view do a queryset that loads the appropriate equities given a portfolio p? or
  3. Is there another way to do this?
Was it helpful?

Solution

I was making things harder than they needed to be. The answer is to make the type of the modelformset_factory "Equity", then make the queryset in my view p.holdings.order_by('symbol'). Now it is working like a charm!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top