coleifer/peewee — Issue #40: is it possible to get select query columns behavior similar to only or exclude in model converter?
Author: davidthewatson
Created: 2012-01-05 03:12:30+00:00
State: open

I have a model where I do something simple:

class Whatever(db.Model):
field1 = CharField()
field2 = CharField()
field3 = CharField()

but in my view I'd like the query to behave like a SQL select. That is, I only get the columns back that I asked for in the select:

whatevers = Whatever.select(Whatever: ['id', "field2"]}) # at this point id and field2 are populated
columns=whatever.model._meta.get_field_names() # this gets me all the fields, not the fields matching the previous select

What I'm wondering is if there's a way to get the columns to match whatever's requested in the query. Obviously, I could do a list comprehension or the like to reduce the column list to the result set, but I'm looking for a more architectural solution - one that's supported within the model. It seemed like there would be something like your ModelConverter's only or exclude parameters, but I couldn't find an example where the select and the column list were matched in this way.

The use case here is simple: I want to be able to generate tables of data in my templates like:

{% for column in columns %}
{{ column }}
{% endfor %}

{% for whatever in whatevers %}

{% for column in columns %}	{% if loop.index == 1: %}{{ whatever[column] }}{% else %}{{ whatever[column] }}{% endif %}{% endfor %}

{% endfor %}

Thanks!