Created
November 12, 2012 21:09
-
-
Save eezis/4061912 to your computer and use it in GitHub Desktop.
Django Question: best way to approach highly conditional page output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
Stocks | |
======= | |
IBM | |
APPL | |
GOOG | |
Bonds | |
======= | |
Boulder, CO 10 year | |
US Treasury 5 year | |
CDs | |
======= | |
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 %} | |
<b>Bonds</b> | |
{% for bond in bond_list %} | |
{% if bond.doc_type=="Bond" %} | |
<li>{ bond.name }}</li> | |
{% endif %} | |
{% endfor %} | |
{% endif %} | |
How would you more experienced Django devs approach this? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.