Skip to content

Instantly share code, notes, and snippets.

Created November 12, 2012 21:09
Show Gist options
  • Save eezis/4061912 to your computer and use it in GitHub Desktop.
Save eezis/4061912 to your computer and use it in GitHub Desktop.
Django Question: best way to approach highly conditional page output
I have this framed out and working but I wanted to post this question to see how more experienced Django developers would approach this problem. So to use a simple domain
that everyone can understand, I will frame this as a simple reporting page on a web site where an investor wants to view different classes of assets (stocks, bonds, cds,
etc). I only show three instrument types but like any project it could grow to many more over the project life cycle.
Given the following models . . .
class Investor(models.Model):
first = models.CharField()
blah = models.CharField()
blan = models.CharField()
class Instrument(models.Model):
STOCK = 'Stock'
BOND = 'Bond'
CD = 'CD'
INST_TYPE_CHOICES = ( (STOCK,'Stock'),(Bond,'Bond'),)
investor = models.ForeignKey(Investor)
instrument_type = models.CharField(max_length='5',choices=INST_TYPE_CHOICES,default=STOCK)
name = . . .
I want the web page to look like this . . .
John Brown
123 Clueless Avenue
Boulder, CO 80303
Boulder, CO 10 year
US Treasury 5 year
Wells Fargo 6 Month
Goldman Sachs Select 2 Year
The complication is that the page is highly conditional. Sometimes all three types (Stocks, Bonds, CDs) will be present, other times,
just one or two types; it's conditional and all possibilities will occur.
MY QUESTION: What is the best way to implement the view/template? With "best" putting a premium on performance, maintainence, general elegance.
I know I could attempt Inclusion Tags, but in my newbness, I am leaning toward making a series of model methods on the Investor class (has_bonds, has_stocks, etc) that
lets me implement a template that looks like this. The drawback is a new model method must get added to the code with every new intrstument type
{% if theinvestor.has_bonds %}
{% for bond in bond_list %}
{% if bond.doc_type=="Bond" %}
<li>{ }}</li>
{% endif %}
{% endfor %}
{% endif %}
How would you more experienced Django devs approach this?
Copy link

eezis commented Nov 13, 2012

After messing around, I decided to simply return the different classes as individual querysets in the view and pass them in the context to the template. I will keep it simple like that unless performance becomes an issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment