Combining Multiple Models Into One Context Variable

Posted on in Programming

Django LogoI'm not sure if the title of this post accurately describes the problem. I have a situation where I have very similar models that I want to display in one table. As you know, querysets are limited to a single model, so it isn't possible to have a single context variable use a single queryset. In my case, I could have created a new context variable for each model, but that results in a situation where adding a new model means changing both the view and the template.

Not surprisingly, Stack Overflow had a great solution. Instead of using multiple context variables, I chained several querysets into one variable. This ended up being the perfect solution.

from itertools import chain
items = (list(chain(qs1, qs2, qs3))

Although akaihola's answer isn't the accepted solution to the question, I find it much nicer.

Further reading:

My Bookshelf

Reading Now

Other Stuff